Can I prevent the assignment of an object?

I want the following type of call to be illegal:

MyClass me; MyClass you; me = you; // how to make this illegal? 

Is it possible?

+6
c ++
source share
7 answers

Declare an assignment statement private:

 class A { private: void operator=(const A&); ... }; 

but they don’t provide an implementation - you will receive a compilation error or link time error message if you try to assign A.

I prefer to use a macro for this. It also prevents copying, while also making the copy constructor private:

 #define CANNOT_COPY( class ) \ private: \ class(const class&); \ void operator=(const class &) \ 

Then I can say things like:

 class A { CANNOT_COPY( A ); ... }; 

which is easy to read and easy to find.

+15
source share

declare the assignment operator as private .

+9
source share

Yes - define a private assignment operator= ( operator= ) or get boost::noncopyable from a convenient class.

+8
source share

Use a constant.

 MyClass const me; MyClass you; me = you; // compilation error 
+2
source share

I use to output my non-copyable classes from a generic noncopyable class. If you are not using boost, I usually use this shortcut:

 class NonCopyable { protected: /** * Protected default constructor */ NonCopyable() {} /** * Protected destructor */ ~NonCopyable() {} private: /** * Private copy constructor */ NonCopyable( const NonCopyable& ); /** * Private assignment operator */ const NonCopyable& operator=( const NonCopyable& ); }; 

Note that neither the copy constructor nor the assignment operators have an implementation.

+1
source share

As in C ++ 11, I understand that the preferred solution is to use the '= delete' construct:

 class MyClass { MyClass (const MyClass&) = delete; // Disable copy constructor MyClass& operator=(const MyClass&) = delete; // Disable assignment ... } 

Then

 MyClass me; MyClass you; me = you; // won't compile 
+1
source share

Other answers are correct here. However, it is important to note that you prohibit only the code you specify. Someone else can come and duplicate their class using memcpy or other strategies.

0
source share

All Articles