禁用编译器生成的复制赋值运算符
当我编写一个类(例如class nocopy
)时,是否可以完全阻止复制运算符的存在?如果我没有定义,而其他人编写了诸如
nocopy A;
nocopy B;
A = B;
编译器之类的内容,则会自动生成一个定义。如果我自己定义一个,我会阻止编译器自动生成,但上面的代码仍然是合法的。
我希望上面的代码是非法的,并生成编译时错误。我该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只需使用
private
访问说明符声明一个复制构造函数,甚至不定义它。任何尝试使用它的人都会收到编译错误,因为它被声明为
私有
。如果有人甚至间接使用它,您将收到链接错误。
在 C++03 中你不能做更多的事情。
但是,在 C++11 中,您可以显式删除特殊成员函数。
例如:
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.
You can't do anything more than that in C++03.
However, In C++11 you can Explicitly delete special member functions.
Eg:
通常的方法是将复制构造函数和赋值运算符声明为私有,这会导致编译错误,就像 Als 解释的那样。
从
boost::noncopyable
派生将为您完成这项工作。The usual way is to declare the copy constructor and the assignment operator to be private, which causes compilation errors, like Als explained.
Deriving from
boost::noncopyable
will do this job for you.如果您从
boost::noncopyable
继承,则在尝试复制构造函数时将收到编译时错误。我发现使用此错误消息(使用 MSVC)是无用的,因为它们通常不指向导致错误的行。另一种方法是声明一个复制构造函数private
并保留其未定义,或者使用BOOST_STATIC_ASSERT(false)
定义它。如果您使用的是 C++11,您还可以删除
您的复制构造函数: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-constructorprivate
and leave it undefined, or define it with aBOOST_STATIC_ASSERT(false)
. If you are working with C++11 you can alsodelete
your copy constructor: