我读了一些关于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