ここはウェブサイトの例です:http://www.cplusplus.com/doc/tutorial/classes2/ 実例です。しかし、私はオブジェクトの温度が演算子+オーバーロード関数から返される理由を理解していません。私はコードの他にいくつかのコメントをしました。C++の関数の中でオブジェクト参照を返すのはなぜですか?
// vectors: overloading operators example
#include <iostream>
using namespace std;
class CVector {
public:
int x,y;
CVector() {};
CVector (int,int);
CVector operator + (CVector);
};
CVector::CVector (int a, int b) {
x = a;
y = b;
}
CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp); ***// Isn't object temp be destroyed after this function exits ?***
}
int main() {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b; ***// If object temp is destroyed, why does this assignment still work?***
cout << c.x << "," << c.y;
return 0;
}
私は、潜在的な最適化については話しません。重要な点は、*意味的に*オブジェクトが関数が完了する前の*戻り値にコピーされていることです( 'return'ステートメントで)。そのコピーが最適化されているかどうかは実装の詳細です。 –