class A {
int value;
public:
A(int value) : value(value) {}
virtual ~A() {
std::cout << "A is destroyed\n";
}
int getValue() const {
return value;
}
};
A *getA() {
returnnew A(7);
}
void doSomething() {
A a = *getA();
std::cout << a.getValue();
}
int main() {
doSomething();
return 0;
}
Basically getA method allocates memory in heap. I de-reference it in doSomething method. It looks like the destructor is called after doSomething is done. Does it mean that original heap memory was cleaned? if yes, why? Was it copied into stack of the function? Or I actually leaked the memory? And if there is a leak, what object was destructed
And if there is a leak, what object was destroyed?
The unnamed object created by getA() has dynamic storage duration. That object is copied into the local object named a inside doSomething(), which has automatic storage duration. That local object (with automatic storage duration) is destroyed when the function returns.
Objects with dynamic storage duration are never destroyed automatically - the programmer is responsible for ensuring they are explicitly deleted.