为什么需要公共副本构造函数,即使它没有被调用? [英] Why is a public copy constructor required even if it is not invoked?
问题描述
拥有公共副本构造函数将使小程序
编译,但不显示副作用复制。
Having a public copy constructor will make the little program compile, but not showing the side effect "Copy".
#include <iostream>
class X
{
public:
X(int) { std::cout << "Construct" << std::endl; }
// Having a public copy constructor will make the little program
// compile, but not showing the side effect "Copy".
private:
X(const X&) { std::cout << "Copy" << std::endl; }
private:
X& operator = (const X&);
};
int main() {
X x = 1;
return 0;
}
推荐答案
所涉及的C ++标准:
Here are the relevant bits of the C++ standard that are involved:
[dcl.init] / 16,bullet 6,子项目1: - 初始化,或者如果是复制初始化,其中源类型的cv非限定版本与目标类的类是相同的或是派生类,则构造函数被考虑.... 如果没有
在其他方面字,无论编译器优化是否可以省略副本,初始化都是错误的,因为没有适用的构造函数。当然,一旦你复制公开,以下部分适用:
In other words, it doesn't matter if a compiler optimization could elide the copy, the initialization is ill-formed because there are no applicable constructors. Of course, once you make the copy constuctor public, the following section applies:
[class.copy] / 31:当某些标准met,允许实现省略类对象的复制/移动构造,即使对于对象的复制/移动构造函数和/或析构函数具有副作用....这种复制/移动操作的检测,称为复制检测,在以下情况下允许(可以组合使用以消除多个副本):
[class.copy]/31: When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects.... This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):
项目符号3:当未绑定到引用的临时类对象12.2)将被复制/移动到具有相同的cv非限定类型的类对象,通过将临时对象直接构造到省略的复制/移动的目标中,可以省略复制/移动操作
bullet 3: when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move
这篇关于为什么需要公共副本构造函数,即使它没有被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!