gpt4 book ai didi

c++ - 为什么不调用构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:03:34 25 4
gpt4 key购买 nike

我已经编写了一个测试类,但我无法理解发生了什么!。

是否删除了移动/复制?如果是这样,如何用新值更新它。我肯定错过了一些东西。

这是测试用例(请不要考虑有用性)

#include<iostream>

struct Test
{
int a;
Test(){a = 10;std::cout<<"def\n";}
Test(int a){this->a = a;std::cout<<"unary\n";}
Test(const Test& a){this->a = a.a; std::cout<<"copy\n";}
Test(Test&& a){this->a = a.a; std::cout<<"Move\n";}
Test& operator=(const Test& a){this->a = a.a;std::cout<<"op=\n";}
Test& operator=(Test&& a){this->a = a.a;std::cout<<"Move=\n";}
void display(){std::cout << "Display ";}
};


Test gi(Test a)
{
std::cout<<a.a<<"&\n";
return a;
}

int main()
{
//Test a = 99;
//Test();
/*Line MST*/ Test b = Test(102);//gi(a);
std::cout<<b.a<<'\n';

return 0;
}

这里的 MST 行是我不明白的。如果我用一个临时的 Test 对象初始化它,它不应该调用 Move 构造函数(或至少是拷贝)吗?

输出是:

unary
102

与此行类似的输出

 Test b = gi(Test(103));

在调用 gi() 期间没有发生移动/复制?

但这是我所期望的

Test a = 99;
Test b = gi(a);

我在这里错过了什么?

最佳答案

Is the Move/copy being elided? if so how could it be updated with the new value

是的,根据 C++11 标准的第 12.8/31 节省略了拷贝。何时以及是否执行此优化完全取决于编译器,您不应期望它是否执行(即使复制构造函数或移动构造函数有副作用)。

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

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