Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between different flavours of shared_ptr

Are there any differences between boost::shared_ptr, std::tr1::shared_ptr and the upcoming (in C++0x) std::shared_ptr?

Will porting from one to another have any overhead or are they basically the same?

like image 846
Motti Avatar asked Jul 06 '09 12:07

Motti


People also ask

What is the difference between the two smart pointers shared_ptr and Unique_ptr?

In short: Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.

Can you describe what Unique_ptr and shared_ptr are and when you would use them?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.

Are shared_ptr slow?

shared_ptr are noticeably slower than raw pointers. That's why they should only be used if you actually need shared ownership semantics. Otherwise, there are several other smart pointer types available. scoped_ptr and auto_ptr (C++03) or unique_ptr (C++0x) both have their uses.

Why do we need shared pointer?

The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.


1 Answers

According to the Boost website, the boost::shared_ptr...

...conforms to the TR1 specification, with the only exception that it resides in namespace boost instead of std::tr1.

According to the Wikipedia C++0x page

The TR1 implementation lacked certain pointer features such as aliasing and pointer arithmetic, but the C++0x version will add these.

If your code works with the TR1/Boost version, it should work with the C++0x version (but not necessarily vice versa).

like image 61
Benjamin Titmus Avatar answered Oct 01 '22 22:10

Benjamin Titmus