我在 C++ 中阅读了一些关于 RVO 的内容,并发现了一个奇怪的观察结果。我运行了下面的代码..
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 下,此代码显示没有内存泄漏,但删除 [] 无效。
我有点困惑如何调用额外的析构函数,为什么没有相应的构造函数调用相同的?