选择退出复制构造函数
这可能是一个愚蠢的问题,但是......
我一直在编写许多使用不可复制成员的类。这些类永远不会通过我的源代码中的复制构造函数初始化。当我尝试在不提供自己的复制构造函数的情况下进行编译时,g++ 会抛出许多错误,说明由于不可复制的成员对象,它无法构建默认的复制构造函数。
有没有办法告诉编译器不要给我复制构造函数?
编辑:是的...感觉很傻...我有一个案例,我在 boost::bind 调用中意外调用了复制构造函数。吸取教训。
This might be a silly question, but...
I've been writing a number of classes that utilize non-copyable members. These classes are never initialized via the copy constructor in my source. When I try to compile without supplying my own copy-constructor, g++ throws out many errors about how it can't build a default copy constructor, due to the non-copyable member objects.
Is there a way to tell the compiler to just not give me a copy constructor?
EDIT: Yeah... feels silly... I had a case where I was invoking the copy-constructor by accident in a boost::bind call. Lesson learned.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使事物不可复制的通常方法是声明但不定义复制构造函数,并将其设为私有,以便没有任何东西可以调用它。
该语言的下一个修订版将提供显式方式来抑制这些生成的函数< /a>.
The usual way to make things noncopyable is to declare but not define a copy constructor, and make it private so nothing can call it.
The next revision of the language will provide an explicit way to suppress these generated functions.
如果您实际上没有导致调用复制构造函数,那么如果编译器无法生成复制构造函数,那么这并不是一个错误。听起来您(可能是间接地)导致使用复制构造函数。
您可以通过声明自己的复制构造函数来抑制编译器生成的编译器(如果不使用它,则不需要定义它)。您可以将其放置在类的
private
部分中。如果这将错误更改为复制构造函数无法访问或出现链接错误,那么您确实导致了复制构造函数被使用,您需要分析原因。
If you don't actually cause the copy-constructor to be called then it is not an error if the compiler would be unable to generate one. It sounds like you are (possibly indirectly) causing the copy-constructor to be used.
You can suppress the compiler generated one by declaring your own copy-constructor (you don't need to define it if you're not using it). You can place it in the
private
section of your class.If this changes the error to say that the copy-constructor is inaccessible or you get link errors then you really are causing the copy-construtor to be used and you need to analyze why this is.
当前版本的 C++ 中没有。在 C++ 0x 中,将有一个
=delete;
语法告诉它,如果您自己没有定义,您不需要编译器默认生成的特殊成员函数之一。Not in the current version of C++. In C++ 0x, there will be an
=delete;
syntax to tell it that you don't want one of the special member functions the compiler will generate by default if you don't defined one yourself.在完全支持新的 C++ 0x 标准之前,您能做的最好的事情就是声明特殊成员函数的版本,但不实现它们。通常它们是私有的(以帮助明确它们不应该被使用)。
Until the new C++ 0x standard is fully supported, the best you can do is to delclare a version of the special member function, but not implement them. Normally they are made private (to help make it clear that they shouldn't be used).
否:)
如果您希望您的类不可复制,请使用诸如
boost::noncopyable
之类的内容,或者在类定义中使用声明私有复制构造函数的参数化宏。
No :)
If you want your class to be non-copyable use something like
boost::noncopyable
or use a parametrizied macro in your class definition that declares a private copy constructor.