Domanda

Is there a difference between:

Foo *foo = new Foo();
shared_ptr<Foo> sp(foo);
_fooVector.push_back(sp);

and

shared_ptr<Foo> sp(new Foo());
_fooVector.push_back(sp);

according to stack and heap. In all examples i can find new is used on the same line where the smart pointer get's created. So i'm wondering if the firs example is valid.

È stato utile?

Soluzione

First example if valid, but it's more exception-safe and correct to use make_shared.

shared_ptr<Foo> sp = make_shared<Foo>();

In your first example - you allocate memory, initialize pointer with this memory, create shared_pointer (shared_ptr now owns memory) and then push copy to vector). In second example - you allocate memory, initialize parameter of shared_ptr c-tor with this memory and then as in first example.

Altri suggerimenti

Is there a difference [...] according to stack and heap

Both make the same use of the heap: one allocation for the Foo object, and one for the shared counter. (Assuming a typical implementation of shared_ptr)

In the first case, foo lasts until the end of the code block, while in the second the temporary pointer only lasts until the end of the declaration. So in principle, the second makes less use of the stack than the first; but in practice, both should be optimised to be (more or less) identical.

Better would be

_fooVector.push_back(std::make_shared<Foo>());

since that only needs to make a single heap allocation for both the Foo object and the shared count.

So i'm wondering if the firs example is valid.

Yes, that's valid - you can initialise a shared pointer with any suitable pointer. It's slightly more dangerous for two reasons: the raw pointer is available to misuse, and it's possible to do something else before assigning it to the smart pointer, opening the possibility of a leak. Initialising directly from the new expression fixes the first danger, but not always the second. Using make_shared fixes both.

from:http://www.cplusplus.com/reference/memory/shared_ptr/shared_ptr/

we have the third constructor allowed is: from pointer (3) template <class U> explicit shared_ptr (U* p);

So yes, the first example is valid.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top