Reputation: 91
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";
Upvotes: 6
Views: 3366
Reputation: 72539
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.
Upvotes: 10
Reputation: 69792
how could I create a new object to assign it to shared pointer?
You have to "reset" the shared pointer :
classA* my_pointer = new classA();
shared_ptr<classA>ptr;
ptr.reset( my_pointer );
how could I assign NULL again to ptr3 so that the if statement below becomes true?
Again, by using reset but with no argument( or null)
ptr3.reset();
Upvotes: 0