在此示例中,我试图了解对象创建和销毁的情况。
#include <iostream>
class Person {
public:
const char* name;
Person(const char* name) : name(name) {
std::cout << "Person " << name << " created" << std::endl;
};
~Person() {
std::cout << "Person " << name << " destroyed" << std::endl;
}
};
class Family {
public:
Person mom, dad;
Family(Person& m, Person& d) : mom(m), dad(d) {
std::cout << "Family created" << std::endl;
};
~Family() {
std::cout << "Family destroyed" << std::endl;
}
};
int main()
{
Person* m = new Person("Jane");
Person* d = new Person("John");
Family f(*m, *d);
return 0;
}
这个输出
Person Jane created
Person John created
Family created
Family destroyed
Person John destroyed
Person Jane destroyed
So I am not entirely sure how to interpret this. I've been taught that anything I heap-allocate using the new
keyword should subsequently be delete
-d. And stack variables are lost when the object moves out of scope. My understanding is like this. If instead of accepting Person& m
by reference I took it without the &
, like Person m
, then m
would be copied here (on the stack) and I'd have a memory leak because the heap-allocated new Person("Jane")
would never be deleted.
But since I am taking it by reference, do I still have a memory leak? Both m
and d
have their destructors called, but does this also free the heap-memory? And how can I think of Family.dad
? Is this a stack variable? If so, then is the entire Family
considered a scope?
I am quite confused by this example and don't really know how to reason about it. Also, do I still have a memory leak here since I never explicitly delete
the two Person
objects?
添加复制构造函数以查看整个图片。
Although
Family::Family
gets the objects by reference, it then copies them into the membersmom
anddad
. So the destructor invocations you observe actually occur when those members get destructed.原始对象不会释放-直到程序退出。
As for the location of
Person
instance and its members - all of them are allocated in the "free store", as per C++ Standard. Typically, it means they reside on the heap.