advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Partners & Affiliates
advertisement
advertisement
advertisement
Average Rating: 3.3/5 | Rate this item | 3 users have rated this item.
 

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. 


advertisement
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_ptr in 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_ptr safely with STL containers and algorithms.


Replace auto_ptr with the new unique_ptr class template.

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


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_ptr is the culprit.

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

  Next Page: Just Like auto_ptr, But Better
Page 1: IntroductionPage 3: The Sink and Source Idiom
Page 2: Just Like auto_ptr, But Better 
Please rate this item (5=best)
 1  2  3  4  5
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs