C++:什么时候隐式复制类?
C++ 中什么时候隐式复制类?
我有一个包含 unique_ptr 的类,因此无法安全地复制,因此,我通过创建 X(X&)
和 X& 的私有版本来禁用该类上的复制构造函数。运算符 = X&
。
我立即遇到了无法返回此类实例的问题,因为返回实际上会生成实例的副本。
还有其他情况需要注意吗?
When is a class implicitly copied in C++?
I have a class that contains a unique_ptr, and therefore cannot be safely copied, and therefore, I disabled the copy constructor on the class by creating private versions of X(X&)
and X& operator = X&
.
I immediately ran into the problem that instances of this class cannot be returned, because returning actually makes a copy of the instance.
Are there any other situations I need to watch out for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
返回并不复制实例,而是移动实例。您只是忘记提供移动构造函数。此外,在大多数情况下,在标准容器中使用类时,类现在会被移动,而这些类以前是被复制的。
简而言之,提供一个移动构造函数和移动赋值运算符(最好是交换),您应该发现几乎所有副本都是隐式的情况,它们现在都是移动。
Returning does not copy the instance, it moves the instance. You just forgot to provide a move constructor. In addition, classes are now moved when used in Standard containers in most situations in which they used to be copied.
In short, provide a move constructor and move assignment operator (and swap, preferably) and you should find that almost all situations where copies are implicit, they're now moves.
想到的情况是:按值接收类的函数、按值返回类的函数以及包含该类的任何类或容器。像 std::vector 这样的类将尽可能使用移动语义(您确实重载了这一点)?但将无法使用需要复制构造函数的函数,例如复制向量。正如 GMan 所说,如果您想让事情变得更容易,您可以为您的类创建一个复制构造函数,并手动执行 std::unique_ptr 的深层复制。
The situations that come to mind are: functions that receives the class by value, functions that returns then class by value, and any class or container that contains that class. Classes like std::vector will use move semantics whenever possible (you did overload that right)? but will be unable to use functions that require a copy constructor, such as copying the vector. As GMan said though, you can make a copy constructor for your class, and do a deep copy of the std::unique_ptr manually, if you want to make things easier.