gpt4 book ai didi

c++ - 使用继承在 C++ 中调用析构函数和销毁成员变量的顺序是什么?

转载 作者:可可西里 更新时间:2023-11-01 16:28:06 26 4
gpt4 key购买 nike

与这些问题非常相似,但不完全相同:What is the order in which the destructors and the constructors are called in C++ Order of member constructor and destructor calls

我想知道:派生类的成员变量是在调用基类的析构函数之前还是之后销毁的?

这是在 C++ 中使用 Visual Studio 2008。谢谢。

最佳答案

构造函数:先基后导出

破坏:

  • ~派生
  • ~成员派生
  • ~基地
  • ~成员(member)群

代码:

class member {
string s;

public:
member(string s) {
this-> s = s;
}

~member() {
cout << "~member " << s << endl;
}
};

class base {
member m;
public:
base() : m("base"){
}

~base() {
cout << "~base" << endl;
}
};

class derived : base{
member m2;
public:

derived() :m2("derived") { }

~derived() {
cout << "~derived" << endl;
}
};

int main(int argc, const char * argv[]) {
derived s;

return 0;
}

引用和虚析构函数

当您计划动态分配(即当您使用关键字 newdelete)派生对象时,总是有一个 virtual 或者你的基础上的 protected 析构函数。动态删除基类引用上的对象否则会导致下面示例中的内存泄漏:

class base {
member m;
public:
base() : m("base"){
}

/* correct behaviour is when you add **virtual** in front of the signature */
~base() {
cout << "~base" << endl;
}
};

class derived : public base{
member m2;
char* longArray;
public:

derived() :m2("derived") {
longArray = new char[1000];
}


~derived() {
delete[] longArray; // never called
cout << "~derived" << endl;
}
};

int main(int argc, const char * argv[]) {
base *s = new derived; // mind the downcast to **base**

delete s; /* only the non-virtual destructor on the base and its members is called.
No destructor on derived or its members is called.
What happens to the memory allocated by derived?
**longArray** is leaked forever.
Even without **longArray**, it most probably **leaks** memory, as C++ doesn't define its behaviour
*/
return 0;
}

输出:

  • ~基地
  • ~成员(member)群

只有基础数据被清理,longArray泄漏

关于c++ - 使用继承在 C++ 中调用析构函数和销毁成员变量的顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28356069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com