0

I want to initialize two instances of a classes through smart pointers:

    std::shared_ptr< myQueue > _pA ;
    std::shared_ptr< myQueue > _pB ;

    _pA.reset( new myQueue() ) ;
    _pB.reset( new myQueue() ) ;

Do I have initialized with the above reset function two different myQueues or just two pointers on the same object?

Smii
  • 38
  • 5
  • Think about how many instance of `myQueue` you have above, hint: `new myQueue()` constructs a *new instance*... If you want the shared pointers to *point to the same instance*, construct one and then assign the pointer to the second pointer... – Nim Dec 09 '13 at 16:18

2 Answers2

6

Assuming your myQueue class isn't weird, yes, you will have two separate instances.

You might also be interested in make_shared, which would let you write it like this:

auto _pA = std::make_shared<myQueue>();
auto _pB = std::make_shared<myQueue>();
kenm
  • 23,127
  • 2
  • 43
  • 62
  • Thanks a lot and I will check on this! – Smii Dec 09 '13 at 16:29
  • +1 - `make_shared` is the preferred way to make a shared pointer, as it puts the object and reference count in a single allocation. – Chad Dec 09 '13 at 16:46
  • 1
    @Chad Or not; I don't think that this is guaranteed. The important thing is that it puts the `new` and the construction of the `shared_ptr` in a single function call, so they can't be reordered with something else that might through. In particular, something like `f( std::make_shared(), std::make_shared() )` is legal, and doesn't risk leaking memory. (Of course, realistically, functions taking a `shared_ptr` should be pretty scarce.) – James Kanze Dec 09 '13 at 17:30
  • You are correct, it's not guaranteed by the standard. Agreed, there are also other (very good) reasons to prefer it. – Chad Dec 09 '13 at 17:37
1

Initializing the two shared_ptr with two pointers to the same object will result in a double delete. You don't ever want to do it.

James Kanze
  • 150,581
  • 18
  • 184
  • 329