Question

That is, if I don't use the copy constructor, assignment operator, or move constructor etc.

int*   number = new int();
auto   ptr1   = std::shared_ptr<int>( number );
auto   ptr2   = std::shared_ptr<int>( number );

Will there be two strong references?

Was it helpful?

Solution 2

Yes there will be two strong references, theres no global record of all shared pointers that it looks up to see if the pointer you're trying to cover is already covered by another smart pointer. (it's not impossible to make something like this yourself, but it's not something you should have to do)

The smart pointer creates it's own reference counter and in your case, there would be two separate ones keeping track of the same pointer.

So either smart pointer may delete the content without being aware of the fact that it is also held in another smart pointer.

OTHER TIPS

According to the standard, use_count() returns 1 immediately after a shared_ptr is constructed from a raw pointer (§20.7.2.2.1/5). We can infer from this that, no, two shared_ptr objects constructed from raw pointers are not "aware" of each other, even if the raw pointers are the same.

Your code is asking for crash!

You cannot have two smart pointers pointing to the same actual object, because both will try to call its destructor and release memory when the reference counter goes to 0.

So, if you want to have two smart pointers pointing to the same object you must do:

auto ptr1 = make_shared<int>(10);
auto ptr2 = ptr1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top