When I'm writing a class (say class nocopy
), is it possible to prevent the existence of the copy operator entirely? If I don't define one, and somebody else writes something like
nocopy A; nocopy B; A = B;
the compiler will auto-generate a definition. If I define one myself, I will prevent the compiler from auto-generating, but the code above will still be legal.
I want the code above to be illegal, and generate a compile time error. How do I do that?
A cleaner solution: create a class where the default copy constructor and/or default copy assignment operator are deleted. Derive all your classes or the base class of the class hierarchies from this special class. Copy construction and/or copy assignment will now be disabled for all these classes automatically.
There are three ways to prevent such an object copy: keeping the copy constructor and assignment operator private, using a special non-copyable mixin, or deleting those special member functions. A class that represents a wrapper stream of a file should not have its instance copied around.
If no user-defined copy assignment operators are provided for a class type (struct, class, or union), the compiler will always declare one as an inline public member of the class.
It is well-known what the automatically-generated assignment operator will do - that's defined as part of the standard and a standards-compliant C++ compiler will always generate a correctly-behaving assignment operator (if it didn't, then it would not be a standards-compliant compiler).
You just declare a copy constructor with private
access specifier and not even define it.
Anyone trying to use it will get an compile error since it is declared private
.
If someone uses it even indirectly, you will get a link error.
You can't do anything more than that in C++03.
However, In C++11 you can Explicitly delete special member functions.
Eg:
struct NonCopyable { NonCopyable & operator=(const NonCopyable&) = delete; NonCopyable(const NonCopyable&) = delete; NonCopyable() = default; };
The usual way is to declare the copy constructor and the assignment operator to be private, which causes compilation errors, like Als explained.
Deriving from boost::noncopyable
will do this job for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With