Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Who's the Smartest of 'Em All? Get to Know std::unique_ptr

C++0x now offers a safer and extremely versatile smart pointer class called std::unique_ptr. Learn how to implement strict ownership semantics with unique_ptr and benefit from its diverse services—customized deleters, safe usage with containers and algorithms, and array handling.


td::auto_ptr was a move semantics pioneer. However, at that time, C++ didn't have the facilities for supporting move operations that were both safe and efficient. After years of distilling, C++0x brings you a superior alternative called unique_ptr. unique_ptr offers the same runtime and size efficiency of auto_ptrin addition to code safety and many other goodies, including array handling, and STL compatibility.

Your program needs a smart pointer that implements the strict ownership semantics but you cannot use auto_ptrsafely with STL containers and algorithms.

Replace auto_ptr with the new unique_ptrclass template.

Presenting the Problem
Suppose your program calls std::sort() to sort a sequence of auto_ptrobjects:

vector<auto_ptr<int> > vi;
//..populate vi
sort(vi.begin(), vi.end(), indirect_less());

Depending on the underlying implementation of sort(), the above call could work perfectly—or it might cause a runtime crash. The problem is that some implementations of sort()pick an element out of the sequence, storing a local copy thereof:

value_type pivot_elem = *midpoint;//not a copy operation!

sort() assumes that pivot_elem and *midpoint are equivalent. However when value_type is an auto_ptr, this assumption fails because what appears to be a copy operation is in fact a move operation. Consequently, the algorithm fails. There's nothing amiss with the implementation of sort(). Rather, auto_ptris the culprit.

Because of such bugs, using auto_ptrwith Standard Library containers and algorithms is forbidden. What other alternative do you have?

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date