c++shared-ptrsmart-pointersunique-ptrauto-ptr

Why is using a reference or unique pointer member of a class a bad thing?


In the book "C++ Coding Standards. 101 Rules, Guidelines, and Best Practices" by Herb Sutter and Andrei Alexandrescu in Rule 52, the final quote is:

"In rare cases, classes that have members of strange types (e.g., references, std::auto_ptrs) are an exception because they have peculiar copy semantics. In a class holding a reference or an auto_ptr, you likely need to write the copy constructor and the assignment operator, but the default destructor already does the right thing. (Note that using a reference or auto_ptr member is almost always wrong.)"

It is clear why using references as members is not a good idea (answer to this question is in this post: Should I prefer pointers or references in member data?)

  1. With regard to a modern C++, does it also mean that using unique_ptr as a class member is usually a bad thing? Or was it a problem only of auto_ptr and missing move semantics maybe?
  2. Should shared_ptr be used for a polymorphic behavior then?

Thanks in advance!


Solution

    1. With regard to a modern C++, does it also mean that using unique_ptr as a class member is usually a bad thing?

    It doesn't meant that, and use of unique pointers isn't a bad thing.

    Or was it a problem only of auto_ptr and missing move semantics maybe?

    The main problem is that copying of auto_ptr transfers ownership of the pointed resource. This is what the author refers to with "peculiar copy semantics".

    Given that const auto_ptr cannot be copied, it is not nearly as dangerous as a non-const one is. It had niche uses, but uses of non-copyable types are quite limited pre-C++11.

    Unique pointer doesn't have peculiar copy semantics. In fact, unique pointers are not copyable at all. This is not as much of a problem in C++11 where a type can be movable. Unique pointers cover all use cases where auto_ptr was usable, as well as others where auto_ptr was treacherous.

    1. Should shared_ptr be used for a polymorphic behavior then?

    Shared pointer can be used, but it is not necessary.

    P.S. auto_ptr was deprecated in C++11, and removed from the standard library completely in C++17.