c++ - Could an optimizing compiler remove all runtime costs from std::unique_ptr? -


reading std::unique_ptr @ http://en.cppreference.com/w/cpp/memory/unique_ptr, naive impression smart enough compiler replace correct uses of unique_ptr bare pointers , put in delete when unique_ptrs destroyed. case? if so, of mainstream optimizing compilers this? if not, possible write some/all of unique_ptrs compile-time safety benefits optimized have no runtime cost (in space or time)?

note (properly) worried premature optimization: answer here won't stop me using std::unique_ptr, i'm curious if it's awesome tool or awesome one.

edit 2013/07/21 20:07 est:

ok, tested following program (please let me know if there's wrong this):

#include <climits> #include <chrono> #include <memory> #include <iostream>  static const size_t iterations = 100;  int main (int argc, char ** argv) {     std::chrono::steady_clock::rep smart[iterations];     std::chrono::steady_clock::rep dumb[iterations];     volatile int contents;     (size_t = 0; < iterations; i++) {         auto start = std::chrono::steady_clock::now();         {             std::unique_ptr<int> smart_ptr(new int(5));             (unsigned int j = 0; j < uint_max; j++)                 contents = *smart_ptr;         }         auto middle = std::chrono::steady_clock::now();         {             int *dumb_ptr = new int(10);             try {                 (unsigned int j = 0; j < uint_max; j++)                     contents = *dumb_ptr;                 delete dumb_ptr;             } catch (...) {                 delete dumb_ptr;                 throw;             }         }         auto end = std::chrono::steady_clock::now();         smart[i] = (middle - start).count();         dumb[i] = (end - middle).count();     }     std::chrono::steady_clock::rep smartavg;     std::chrono::steady_clock::rep dumbavg;     (size_t = 0; < iterations; i++) {         smartavg += smart[i];         dumbavg += dumb[i];     }     smartavg /= iterations;     dumbavg /= iterations;      std::cerr << "smart: " << smartavg << " dumb: " << dumbavg << std::endl;     return contents; } 

compiling g++ 4.7.3 using g++ --std=c++11 -o3 test.cc gave smart: 1130859 dumb: 1130005, means smart pointer within 0.076% of dumb pointer, surely noise.

it expectation reasonably competent compiler, since wrapper around simple pointer , destructor calls delete, machne code generated compiler for:

x *p = new x; ... stuff p.  delete p;  

and

unique_ptr<x> p(new x); ... stuff p;  

will same code.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -