i was reading a bit about RVO in c++, and found a weird observation. I ran the below code..
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;
}
i got the o/p as
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
the temporary copy variable in the call to testFunc actually causes some issue. it deletes the ptr member of var1, which can be seen by the call to the destructor in the pointer 0xbfe3e918. under valgring this code show no mem leaks but invalid delete[].
i was bit confused how the extra destructor is being called and why no corresponding constructor call for the same ??