开发者

Can I prevent object assignment?

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?


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.


declare the assignment operator as private.


Yes - define a private assignment operator (operator=) or derive from the handy boost::noncopyable class.


As of C++11, my understanding is 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


Use const.

MyClass const me;
MyClass you;
me = you; // compilation error


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜