c++ - 拷贝初始化是否与拷贝的拷贝初始化相同?

标签 c++ initialization copy-elision copy-initialization

以下两个代码段展示了将变量 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 之前的模式和禁止优化的选项进行编译,您可能会看到这两种情况之间的区别。

LIVE

关于c++ - 拷贝初始化是否与拷贝的拷贝初始化相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65194182/

相关文章:

c# - 字节到签名短

c++ - 为什么没有编译错误呢?

java - init block 阻塞了构造函数?

c++ - 在cpp文件中初始化一个私有(private)静态成员变量。错误 : member is private

c++ - 什么是复制省略和返回值优化?

c++ - 拷贝省略和虚拟克隆

C++ 字节数组到 int

c++ - 多类型分配器设计

java - final 字段可能尚未/已经初始化

c++ - 为什么通过构造函数返回对象时没有临时对象?