以下两个代码段展示了将变量 b
初始化为 a
的拷贝的任务。第一个代码段使用复制初始化(初始化使用=
)初始化变量。假设类 Apple
被简单地定义为一个空类:class Apple {};
Apple a;
Apple b = a;
第二个代码段也使用复制初始化来初始化变量。虽然初始化时复制的是a
的拷贝。
Apple a;
Apple b = Apple(a);
当盲目阅读时,似乎在 Apple(a)
发生了一个拷贝,在 Apple b = ...
发生了另一个拷贝。矛盾的是,重写 Apple
的复制构造函数以在拷贝上打印某些内容表明在 Apple b = Apple(a)
期间只发生了一次复制。
Apple b = a;
和 Apple b = Apple(a);
这两个语句是否相同?是否存在它们不相同的情况?
最佳答案
是的,在概念上,对于Apple b = Apple(a);
,一个临时的Apple
首先从a
构造,然后b
是从临时文件复制初始化的。因为copy elision ,因为效果 b
是直接从 a
初始化的。
Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:
- In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type:
这种复制省略从 C++17 开始得到保证,在 C++17 之前它是一种优化。使用 C++17 之前的模式和禁止优化的选项进行编译,您可能会看到这两种情况之间的区别。
关于c++ - 拷贝初始化是否与拷贝的拷贝初始化相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65194182/