I want to ensure that the following type of call is illegal:
MyClass me;
MyClass you;
me = you; // how to make this illegal?
Is it possible?
I want to ensure that the following type of call is illegal:
MyClass me;
MyClass you;
me = you; // how to make this illegal?
Is it possible?
Yes - define a private assignment operator (operator=) or derive from the handy boost::noncopyable class.
Use const.
MyClass const me;
MyClass you;
me = you; // compilation error
Declare the assignment operator private:
class A {
private:
void operator=(const A&);
...
};
but don't provide an implementation - you will get a compile or link-time error if you try to perform an assignment to A.
I prefer to use a macro to do this. This also prevents copying, by making the copy constructor private too:
#define CANNOT_COPY( class ) \
private: \
class(const class&); \
void operator=(const class &) \
I can then say things like:
class A {
CANNOT_COPY( A );
...
};
which is easy to read and easy to search for.
I use to derive my noncopyable classes from a common noncopyable class. If 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.
The other answers here are all correct. However, it is important to note that you are only prohibiting the specific code you mentioned. Someone can still come along and make a duplicate of your class by using memcpy or other strategies.