Item 6. Explicitly disallow the use of compile-generated functions you do not want.
本篇条目介绍了如何防止编译器调用其自动创建的函数(item5中提到的4种函数)。
Usually, if you don‘t want a class to support a particular kind of functionality, you simply don‘t declare the function that would provide it. But sometimes as the Item 5 points out, if
you don‘t declare them and somebody tries to call them, compilers declare them for you.
Here are some ways to prevent compiler generated functions:
The key to the solution is that all the compiler generated functions are public. To prevent these functions from being generated, you must declare them yourself, but there is nothing that requires that you declare them public. Instead, declare the
copy constructor and the copy assignment operator private. By declaring a member function explicitly, you prevent compilers from generating their own version, and by making the function private, you keep people from calling it.
But member and friend function can still call this private functions. So, another trick is declaring member functions private and deliberately not implementing them.
class NonCom{ public: ..... private: NonCom(const NonCom&); NonCom& operator=(const NonCom&); ... };If you inadvertently try to do call this function in a member or a friend function, the linker will complain.
It‘s possible to move the link- time error up to compile time (always a good thing—earlier error detection is better than later) by declaring the copy constructor and copy assignment operator private not in NonCom itself, but in a base
class specifically designed to prevent copying. The base class is simplicity itself:
class noncopyable{ public: noncopyable(){} ~noncopyable(){} private: noncopyable(const noncopyable&); noncopyable& operator=(const noncopyable&); }; class NonCom : noncopyable{ ... };This works, because compilers will try to generate a copy constructor and a copy assignment operator if anybody — even a member or friend function — tries to copy a NonCom object. As Item 12 (See 10.8) explains, the compiler- generated versions of these functions will try to call their base class counterparts, and those calls will be rejected, because the copying operations are private in the base class.
Things to Remember
- To disallow functionality automatically provided by compilers, declare the corresponding member functions private and give no implementations. Using a base class like Uncopyable is one way to do this.
《Effective C++》读书笔之六 Item 6. Explicitly disallow the use of compile-generated functions