Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable compiler-generated copy-assignment operator [duplicate]

Tags:

c++

copy

class

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?

like image 993
Malabarba Avatar asked Oct 19 '11 15:10

Malabarba


People also ask

How do I turn off assignment operator?

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.

How do I stop copying in C++?

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.

What happens if you dont define a copy assignment operator?

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.

Is assignment operator automatically generated?

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).


2 Answers

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; }; 
like image 54
Alok Save Avatar answered Sep 19 '22 02:09

Alok Save


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.

like image 37
thiton Avatar answered Sep 19 '22 02:09

thiton