禁用编译器生成的复制赋值运算符 [英] Disable compiler-generated copy-assignment operator
问题描述
当我写一个类(例如 class nocopy
)时,是否可以完全防止复制操作符的存在?如果我没有定义一个,而有人写了一些像
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?
推荐答案
只需使用 private $ c $声明一个复制构造函数c>访问说明符,甚至不定义它。
任何试图使用它的人都会得到一个编译错误,因为它被声明为 private
。
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.
但是,在C ++ 11中,您可以 显式删除特殊成员函数 。
However, In C++11 you can Explicitly delete special member functions.
例如:
struct NonCopyable {
NonCopyable & operator=(const NonCopyable&) = delete;
NonCopyable(const NonCopyable&) = delete;
NonCopyable() = default;
};
这篇关于禁用编译器生成的复制赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!