c++ - Basic syntax question for shared_ptr -
i new shared_ptr. have few questions regarding syntax of c++0x shared_ptr below:
//first question shared_ptr<classa>ptr(new classa()); //works shared_ptr<classa>ptr; ptr = ?? //how create new object assign shared pointer? //second question shared_ptr<classa>ptr2; //could tested null if statement below shared_ptr<classa> ptr3(new classa()); ptr3 = ?? //how assign null again ptr3 if statement below becomes true? if(!ptr3) cout << "ptr equals null";
shared_ptr<classa> ptr; ptr = shared_ptr<classa>(new classa(params)); // or: ptr.reset(new classa(params)); // or better: ptr = make_shared<classa>(params); ptr3 = shared_ptr<classa>(); // or ptr3.reset();
edit: summarize why make_shared
preferred explicit call new
:
some (all?) implementation use 1 memory allocation object constructed , counter/deleter. increases performance.
it's exception safe, consider function taking 2 shared_ptrs:
f(shared_ptr<a>(new a), shared_ptr<b>(new b));
since order of evaluation not defined, possible evaluation may be: construct a, construct b, initialize
share_ptr<a>
, initializeshared_ptr<b>
. if b throws, you'll leak a.separation of responsibility. if
shared_ptr
responsible deletion, make responsible allocation too.
Comments
Post a Comment