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.