I am new to the shared_ptr. I have a few questions regarding the syntax of C++0x shared_ptr as below:
//first question
shared_ptr<classA>ptr(new classA()); //works
shared_ptr<classA>ptr;
ptr = ?? //how could I create a new object to assign it to shared pointer?
//second question
shared_ptr<classA>ptr2; //could be tested for NULL from the if statement below
shared_ptr<classA> ptr3(new classA());
ptr3 = ?? //how could I assign NULL again to ptr3 so that the 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: Just to summarize why make_shared
is preferred to an explicit call to new
:
Some (all?) implementation use one memory allocation for the object constructed and the counter/deleter. This increases performance.
It's exception safe, consider a function taking two shared_ptrs:
f(shared_ptr<A>(new A), shared_ptr<B>(new B));
Since the order of evaluation is not defined, a possible evaluation may be: construct A, construct B, initialize share_ptr<A>
, initialize shared_ptr<B>
. If B throws, you'll leak A.
Separation of responsibility. If shared_ptr
is responsible for deletion, make it responsible for the allocation too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With