gpt4 book ai didi

c++使用返回的对象来初始化对象

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:17 24 4
gpt4 key购买 nike

我对C++的返回值机制很疑惑,写了下面的代码来证明我的观点,代码的结果(后面有“?”,输出是粗体)让我很困惑,谁能解释一下为什么它会这样输出,或者只是因为我的编译器供应商 (MS Visual C++) 为我优化了?

#include <iostream>

class WInt
{
public:
WInt( int a ) : a(a){ std::cout << a << " " << "A constructor" << std::endl; }
WInt( const WInt& a )
{
std::cout << "copy constructor run" << std::endl;
this->a = a.a;
}
~WInt(){ std::cout << "WInt destructor" << std::endl; }

WInt& operator=( const WInt& v )
{
std::cout << "assignment operator" << std::endl;
this->a = v.a;
return *this;
}

friend const WInt operator+( const WInt& v1, const WInt& v2 )
{
return WInt( v1.a + v2.a );
}

private:
int a;
};

int main( int argc, char* argv[] )
{
std::cout << "-----------" << std::endl;
WInt a(1); // run constructor
WInt b(2); // run constructor

std::cout << "-----------" << std::endl;
WInt c = a + b; // ???????????????????

std::cout << "-----------" << std::endl;
WInt d( a + b ); // ???????????????????

std::cout << "-----------" << std::endl;
c = a + b + c; // run the +, +, =, ~, ~

std::cout << "-----------" << std::endl;
WInt e = c; // run copy constructor

std::cout << "-----------" << std::endl;

return 0;
}

输出是:

-----------

1 A constructor

2 A constructor

-----------

**3 A constructor**

-----------

**3 A constructor**

-----------

3 A constructor

6 A constructor

assignment operator

WInt destructor

WInt destructor

-----------

copy constructor run

-----------

WInt destructor

WInt destructor

WInt destructor

WInt destructor

WInt destructor

最佳答案

这是 return value optimization .您的编译器正在优化不必要的拷贝(尽其所能)。

编辑:检查 this进一步解释的问题。

关于c++使用返回的对象来初始化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17626917/

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