我想确保以下类型的电话是非法的:
MyClass me;
MyClass you;
me = you; // how to make this illegal?
有可能吗?
答案 0 :(得分:15)
声明赋值运算符private:
class A {
private:
void operator=(const A&);
...
};
但不提供实现 - 如果您尝试对A执行分配,则会出现编译或链接时错误。
我更喜欢使用宏来执行此操作。这也可以通过将复制构造函数设为私有来防止复制:
#define CANNOT_COPY( class ) \
private: \
class(const class&); \
void operator=(const class &) \
然后我可以说:
class A {
CANNOT_COPY( A );
...
};
易于阅读且易于搜索。
答案 1 :(得分:9)
将赋值运算符声明为private
。
答案 2 :(得分:8)
是 - 定义私有赋值运算符(operator=
)或派生于方便的boost::noncopyable
类。
答案 3 :(得分:2)
使用const。
MyClass const me;
MyClass you;
me = you; // compilation error
答案 4 :(得分:2)
从C ++ 11开始,我的理解是首选的解决方案是使用the '= delete' construct:
class MyClass {
MyClass (const MyClass&) = delete; // Disable copy constructor
MyClass& operator=(const MyClass&) = delete; // Disable assignment
...
}
然后
MyClass me;
MyClass you;
me = you; // won't compile
答案 5 :(得分:1)
我用来从一个普通的不可复制的类派生我的不可复制的类。如果不使用boost,我通常会使用这个快捷方式:
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& );
};
请注意,复制构造函数和赋值运算符都没有实现。
答案 6 :(得分:0)
这里的其他答案都是正确的。但是,请务必注意,您只是禁止使用您提到的特定代码。有人仍然可以使用memcpy或其他策略来复制你的课程。