When std::make_shared(new Foo())
is called, it constructs a Foo and returns a std::shared_ptr<Foo>
for the caller (viz. here). If this is called multiple times from various objects, does it construct a new Foo()
each time? In this case is it no different than each caller getting a single reference to a new object, acting in practicality like a unqiue_ptr?
Or does it make one Foo()
the first time and then subsequently returning std::shared_ptr
s to it, knowing that it will act like a Singleton of sorts (and of course deleting once the last std::shared_ptr
is destroyed)? Is this platform specific?
Specifically a function as such:
std::shared_ptr<Foo> makeFoo()
{
return std::make_shared<Foo>();
}
No, std::make_shared<Foo>()
will always create a new Foo object and return the managed pointer to it.
The difference to unique_ptr
is, that you can have multiple references to your pointer, while unique_ptr
has only one living reference to your object.
auto x = std::make_shared<Foo>();
auto y = x; // y and x point to the same Foo
auto x1 = std::make_unique<Foo>();
auto y1 = x1; // Does not work