Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can different smart pointers refer to the same object?

It's possible to have weak_ptr along with shared_ptr. But I wanted to know if it is possible to create a shared_ptr and unique_pointer referencing to the same object. If yes, which rule has to be followed ?

like image 519
Ahmed U3 Avatar asked Oct 24 '25 00:10

Ahmed U3


1 Answers

If you create a unique_ptr and a shared_ptr to the same object, they will not know about each other. Therefore, you will end up with a "double free" error, not to mention that you might inadvertently dereference one pointer when the other one has already been freed.

In short, don't do it. If you need to transfer ownership from a unique_ptr to a shared_ptr or vice versa, call release() on the "old" pointer when you create the "new" one.

To your question about "which rule will be followed," the answer is both. Each smart pointer will follow its own rules, but the overall system behavior will be erroneous. The same as if you create a single smart pointer from a raw pointer before or after calling delete yourself.

Note that the same advice applies to creating two unique_ptrs or two shared_ptrs to the same raw pointer. The fact that you're mixing types of smart pointers is not really relevant.

like image 119
John Zwinck Avatar answered Oct 26 '25 15:10

John Zwinck