1
我對C++的返回值機制感到困惑,並且我編寫了以下代碼來證明我的opion和代碼的結果(在它後面有「?」,輸出是大膽)混淆了我,任何人都可以解釋爲什麼它輸出,或者只是因爲我的編譯器供應商(MS Visual C++)爲我優化?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
我覺得下面的鏈接將是有益的: 「http://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization」 –