简体   繁体   中英

Is it necessary to block the assignment operator and the copy constructor when using smart pointers?

I've seen in several places the advice to either define your own assignment operator/copy constructor, or to block the default ones by declaring them private.

However, the only danger I've been able to find was the problem of creating copies of pointers that could be dangling pointers later.

In modern C++ pointers are rare, and most classes just use smart pointers (eg from boost or from the std library in C++11). Is it still necessary to declare the assignment operator and the copy constructor for classes that have no raw pointers?

And mainly: What are the dangers of not doing that? What kind of unexpected behavior can occur?

Not it's not necessary to hide those operators. std::unique_ptr already is noncopyable(you can only move it). And other kinds - std::shared_ptr will increment internal ref count, std::weak_ptr will do nothing since it has lock method. You can read more here (Boost libs)

This is explained in the question What is The Rule of Three?

Also there is a very good explanation on the following website:

Can I trust the Compiler-Generated Copy Constructor and Assignment Operator?

Compiler-generated code is your best friend, provided that you adhere to good style OO practices and know the rules. As explained in part I, the compiler- generated copy constructor and assignment operator perform member-wise copying of user-declared data members. By replacing low-level datatypes -- raw pointers and char arrays for instance -- with their high-level Standard Library counterparts std::tr1::shared_ptr and std::string, not only are you eliminating the onerous bugs associated with manual resource management, you're also guaranteeing that the compiler-generated copy constructor and assignment operator will do the right thing.

The danger with not defining your own assignment operator/copy/move constructor is the possibility of unexpected behavior. These operations are very easily invoked without you being aware of that, causing the unexpected behavior. Declaring them as private will result in compilation error on such occasions.

Also note that not everywhere smart pointers are used. There are more restricted environments (such as kernel, embedded etc.) that generally won't have STL or boost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM