我讀了一些關於RVO的C++,並發現了一個奇怪的觀察。我跑到下面的代碼..問題與返回值優化
class myClass {
private:
int *ptr;
static int id;
public:
myClass() {
id++;
ptr = new int[10];
printf("Created %p id %d this %p\n", ptr, id, this);
}
~myClass() {
delete[] ptr;
ptr = NULL;
printf("Deleted ptr id %d this %p\n", this->id, this);
id--;
}
};
int myClass::id = 0;
myClass testFunc(myClass var) {
myClass temp;
return temp;
}
int main() {
myClass var1, var2;
testFunc(var1);
return 0;
}
我得到的O/P爲
Created 0x9b14008 id 1 this 0xbfe3e910
Created 0x9b14038 id 2 this 0xbfe3e914
Created 0x9b14068 id 3 this 0xbfe3e91c
Deleted ptr id 3 this 0xbfe3e91c
Deleted ptr id 2 this 0xbfe3e918
Deleted ptr id 1 this 0xbfe3e914
Deleted ptr id 0 this 0xbfe3e910
在調用testFunc臨時副本變量實際上會導致一些問題。它刪除了var1的ptr成員,這可以通過調用指針0xbfe3e918中的析構函數來看到。在valgring這個代碼顯示沒有內存泄漏,但無效刪除[]。
我有點困惑如何額外的析構函數被調用,爲什麼沒有相應的構造函數調用相同?
規則3(5)...複製構造函數... – Jarod42 2014-08-30 16:12:31
可能重複[什麼是三條規則?](http://stackoverflow.com/questions/4172722/what-is-the-rule -of-three) – 2014-08-30 16:16:39