Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic syntax question for shared_ptr

Tags:

c++

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";
like image 998
Leslieg Avatar asked Dec 01 '10 09:12

Leslieg


1 Answers

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:

  1. Some (all?) implementation use one memory allocation for the object constructed and the counter/deleter. This increases performance.

  2. 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.

  3. Separation of responsibility. If shared_ptr is responsible for deletion, make it responsible for the allocation too.

like image 126
Yakov Galka Avatar answered Sep 22 '22 10:09

Yakov Galka