C++ 禁用编译器生成的复制赋值运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7823845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Disable compiler-generated copy-assignment operator
提问by Malabarba
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
当我在写一个类(比如class nocopy
)时,是否可以完全阻止复制运算符的存在?如果我不定义一个,而其他人会写类似的东西
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?
我希望上面的代码是非法的,并生成一个编译时错误。我怎么做?
回答by Alok Save
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
.
您只需使用private
访问说明符声明一个复制构造函数,甚至没有定义它。
任何尝试使用它的人都会收到编译错误,因为它是声明的private
。
If someone uses it even indirectly, you will get a link error.
如果有人间接使用它,您将收到链接错误。
You can't do anything more than that in C++03.
在 C++03 中你不能做更多的事情。
However, In C++11 you can Explicitly delete special member functions.
但是,在 C++11 中,您可以显式删除特殊成员函数。
Eg:
例如:
struct NonCopyable {
NonCopyable & operator=(const NonCopyable&) = delete;
NonCopyable(const NonCopyable&) = delete;
NonCopyable() = default;
};
回答by thiton
The usual way is to declare the copy constructor and the assignment operator to be private, which causes compilation errors, like Als explained.
通常的方法是将复制构造函数和赋值运算符声明为私有,这会导致编译错误,就像 Als 解释的那样。
Deriving from boost::noncopyable
will do this job for you.
派生自boost::noncopyable
将为您完成这项工作。
回答by K-ballo
If you inherit from boost::noncopyable
you will get a compile time error when the copy constructor is attempted. I have found that using this the error messages (with MSVC) are useless, since they generally don't point to the line that caused the error. The alternative is to declare a copy-constructor private
and leave it undefined, or define it with a BOOST_STATIC_ASSERT(false)
. If you are working with C++11 you can also delete
your copy constructor:
如果您继承自boost::noncopyable
,则在尝试复制构造函数时会出现编译时错误。我发现使用这个错误消息(使用 MSVC)是无用的,因为它们通常不指向导致错误的行。另一种方法是声明一个复制构造函数private
并使其未定义,或者使用BOOST_STATIC_ASSERT(false)
. 如果您正在使用 C++11,您还delete
可以使用复制构造函数:
class nocopy
{
nocopy( nocopy const& ) = delete;
};