3
可能重複:
What are copy elision and return value optimization?爲什麼我的拷貝構造函數不被調用?
我有以下程序:
#include <iostream>
using namespace std;
class Pointt {
public:
int x;
int y;
Pointt() {
x = 0;
y = 0;
cout << "def constructor called" << endl;
}
Pointt(int x, int y) {
this->x = x;
this->y = y;
cout << "constructor called" << endl;
}
Pointt(const Pointt& p) {
this->x = p.x;
this->y = p.y;
cout << "copy const called" << endl;
}
Pointt& operator=(const Pointt& p) {
this->x = p.x;
this->y = p.y;
cout << "op= called" << endl;
return *this;
}
};
Pointt func() {
cout << "func: 1" << endl;
Pointt p(1,2);
cout << "func: 2" << endl;
return p;
}
int main() {
cout << "main:1" << endl;
Pointt k = func();
cout << "main:2" << endl;
cout << k.x << " " << k.y << endl;
return 0;
}
我期望的輸出如下:
main:1
func: 1
constructor called
func: 2
copy const called
op= called
main:2
1 2
但我得到以下幾點:
main:1
func: 1
constructor called
func: 2
main:2
1 2
的問題是:爲什麼不從FUNC返回一個對象,以主打電話給我拷貝構造函數?
我明白你爲什麼期望複製構造函數被調用,但你不應該期望賦值操作符被調用。當在初始化中使用「'='」時,實際上不是賦值運算符,而是複製初始化(在這種情況下優化了)。如果沒有優化,將會有2次調用拷貝構造函數。 –