Possible Duplicates:
pimpl: shared_ptr or unique_ptr
smart pointers (boost) explained
Could someone explain differences between shared_ptr and unique_ptr?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Both of these classes are smart pointers, which means that they automatically (in most cases) will deallocate the object that they point at when that object can no longer be referenced. The difference between the two is how many different pointers of each type can refer to a resource.
When using
unique_ptr, there can be at most oneunique_ptrpointing at any one resource. When thatunique_ptris destroyed, the resource is automatically reclaimed. Because there can only be oneunique_ptrto any resource, any attempt to make a copy of aunique_ptrwill cause a compile-time error. For example, this code is illegal:However,
unique_ptrcan be moved using the new move semantics:Similarly, you can do something like this:
This idiom means "I’m returning a managed resource to you. If you don’t explicitly capture the return value, then the resource will be cleaned up. If you do, then you now have exclusive ownership of that resource." In this way, you can think of
unique_ptras a safer, better replacement forauto_ptr.shared_ptr, on the other hand, allows for multiple pointers to point at a given resource. When the very lastshared_ptrto a resource is destroyed, the resource will be deallocated. For example, this code is perfectly legal:Internally,
shared_ptruses reference counting to track how many pointers refer to a resource, so you need to be careful not to introduce any reference cycles.In short:
unique_ptrwhen you want a single pointer to an object that will be reclaimed when that single pointer is destroyed.shared_ptrwhen you want multiple pointers to the same resource.