The easiest thing to think about is declaring the copy constructor and the assignment function as private. However, private only says that the external cannot be called directly, but it can be accessed indirectly through the class's member function and the friend function. So what do we do?
----"In a class, it is permissible to declare a function, but it is not possible to implement the function, which is legal. So even if the function is declared in public, but not implemented, then calling this function will also make an error.
Well, we can use the feature together,boost::noncopyable .
[CPP]View PlainCopy
- #ifndef boost_noncopyable_hpp_included
- #define Boost_noncopyable_hpp_included
- Namespace Boost {
- Private copy constructor and copy assignment ensure classes derived from
- Class Noncopyable cannot be copied.
- Contributed by Dave Abrahams
- namespace Noncopyable_ //protection from unintended ADL
- {
- class Noncopyable
- {
- protected:
- Noncopyable () {}
- ~noncopyable () {}
- private: //Emphasize the following members is private
- Noncopyable ( const noncopyable&);
- Const noncopyable& operator= ( const noncopyable&);
- };
- }
- typedef noncopyable_::noncopyable Noncopyable;
- } //namespace Boost
- #endif//boost_noncopyable_hpp_included
In order to prohibit copying of objects, we only need to let their private inherit from Boost::noncopyable,
Class student:private boost::noncopyable
{
......
}
When copying a copy constructor or assignment function called to a derived class, it is unavoidable to call the corresponding function of the base class, because these operations are private, and such operations are rejected by the compiler.
It is important to note that multiple inheritance can sometimes invalidate an empty base class noncopyable optimization, so this is not suitable for multiple inheritance scenarios.
In addition, if you just don't want to use the default copy constructor or assignment function, you can use the delete provided by C++11,
Class MyClass
{
Public
MyClass () =default;
MyClass (const myclass&) =delete;
......
}
Of course, once the function has been deleted, overloading the function is also illegal, which we are accustomed to call a delete function.
How C + + prohibits copying operations for objects