c++ - 复制构造函数不调用

标签 c++ constructor

当我阅读有关复制初始化与直接初始化的文章时 here .复制构造函数应该调用复制初始化。为什么这里复制构造函数不调用?

#include <iostream>

using namespace std;

class A{};

class B{
public:
B(const A &a){cout << "B construct from A" << endl;}
B(const B &b){cout << "B copy constructor" << endl;}
};

int main(){
A a;
B b = a;
return 0;
}

最佳答案

这是复制省略引用 1:
编译器可以通过创建内联对象来优化生成临时对象时的复制构造函数调用,这是 C++ 标准明确允许的。

标准中也通过示例很好地证明了这一点:

C++03 标准 12.2 临时对象 [class.temporary]
第 2 段:

[Example:
class X {
    // ...
    public:
    // ...
    X(int);
    X(const X&);
    ˜X();
};
X f(X);

void g()
{
    X a(1);
    X b = f(X(2));
    a = f(a);
}

Here, an implementation might use a temporary in which to construct X(2) before passing it to f() using X’s copy-constructor; alternatively, X(2) might be constructed in the space used to hold the argument. Also, a temporary might be used to hold the result of f(X(2)) before copying it to `b usingX’s copyconstructor; alternatively,f()’s result might be constructed in b. On the other hand, the expressiona=f(a)requires a temporary for either the argument a or the result off(a)to avoid undesired aliasing ofa`. ]

引用 1:
C++03 12.8 复制类对象[class.copy]
第 12 段:

When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects.....

关于c++ - 复制构造函数不调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12686099/

相关文章:

parameters - 非默认构造函数中的IOC容器处理状态参数

c# - 使用隐式/显式转换而不是构造函数的原因是什么?

c++ - 构造函数中的数组设置意味着稍后失败

c++ - 我可以在前向声明的类中使用类型吗?

c++ - 将 8bpp 位图转换为 32bpp 位图 C++

c++ - 这是在传递 int num 时创建搜索函数的正确方法吗?使用链表库

c++ - std::stoi - 具有非数字字符的字符串被解析为整数而不抛出异常 (c++)

php - 是否将大量参数传递给 parent::__construct 代码异味/糟糕的 OOP?

c++ - C++中的构造函数继承

c++ - #defined 函数只能接受原始输入而不是变量?