gpt4 book ai didi

c++ - 在临时对象上复制构造函数 c++

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:04:55 26 4
gpt4 key购买 nike

#include <iostream>
using namespace std;

class A
{
int x;

public:
A(int c) : x(c) {}
A(const A& a) { x = a.x; cout << "copy constructor called" << endl;}
};

class B
{
A a;

public:
B(int c) : a(c) {}
B(const B& b) : a(b.a) { }
A get_A() { return a;}
};

int main()
{
B b(10);
A a1 = b.get_A();

}

在上面的代码中,我预计“调用复制构造函数”消息会弹出两次,因为首先,b.get_A() 将创建一个调用复制构造函数 (1) 的临时对象,其次,它将复制其引用到 a1 的复制构造函数 (2) ,从而显示两条消息。

但是,该代码实际上会产生一条“已调用复制构造函数”消息。为什么?

最佳答案

C++ 标准允许 copy constructor to be elided在某些情况下。通常,这意味着对象是否将从临时变量复制构造。它可以就地 build 。

在这种情况下,get_A(); 返回了一个拷贝,变成了一个临时的。然后,您将 a1 分配给该临时变量。允许编译器省略额外的拷贝并使用 get_A() 的返回值构造 a1

即使复制构造函数有副作用,也可以进行这种优化。

Copy elision is the only allowed form of optimization that can change the observable side-effects. Because some compilers do not perform copy elision in every situation where it is allowed, programs that rely on the side-effects of copy/move constructors and destructors are not portable.

关于c++ - 在临时对象上复制构造函数 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16757017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com