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

1.5k views Asked by At

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!

2

There are 2 answers

1
eerorika On BEST ANSWER
  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.

12
rashmatash On

Using a unique_ptr member is not a bad practice since the class it's a member of is the owner of the allocated object. However, it will complicate how the class containing it is handled since it prevents the class from being copyable. So, if the class contains any other non-trivial members, then you'll have to write a move constructor, move assignment operator and a destructor for your class.

On the contrary, I'd consider using shared_ptr as class members a bad practice, since it doesn't imply any kind of ownership and causes a non-deterministic object life-time in your code since you have no idea when the last instance of the object held by shared_ptr is freed.