This question already has an answer here:
- Disable copy constructor 3 answers
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?
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:
If you inherit from
boost::noncopyable
you will get a compile time error when the copy constructor is attempted. I have found that using this the error messages (with MSVC) are useless, since they generally don't point to the line that caused the error. The alternative is to declare a copy-constructorprivate
and leave it undefined, or define it with aBOOST_STATIC_ASSERT(false)
. If you are working with C++11 you can alsodelete
your copy constructor: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.