c++ - 析构函数的功能

标签 c++ destructor

对于这样一个简单的类:

class X {
public:
//...
private:
int *ptr;
};

X::~X() {
delete ptr;
}

我写了一个析构函数来释放 ptr 指向的内存。现在,我想知道,如果我的析构函数保持这样,那么什么时候 ptr 才真正被销毁?

谢谢

最佳答案

我认为this article可能会回答您的大部分问题

"Destructors are implicitly called when an automatic object (a local object that has been declared auto or register, or not declared as static or extern) or temporary object passes out of scope. They are implicitly called at program termination for constructed external and static objects. Destructors are invoked when you use the delete operator for objects created with the new operator."

更具体地说:

"The destructors of base classes and members are called in the reverse order of the completion of their constructor:

The destructor for a class object is called before destructors for members and bases are called.

Destructors for nonstatic members are called before destructors for base classes are called.

Destructors for nonvirtual base classes are called before destructors for virtual base classes are called."

关于c++ - 析构函数的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20167870/

相关文章:

java - 面试题: Check if one string is a rotation of other string

C++ 就地析构函数编译警告

c++ - 为什么析构函数不释放数组内存?

c++ - 如何在 C++ 异常类析构函数中释放变量

c++ - 无法解释编译器的行为

c++ - 使用 C++11 智能指针时,你能忘记 Checked-Delete 吗?

c++ - 设置未知长度整数类型的高位

c++ - VS2013 默认初始化 vs 值初始化

c++ - 在树结构中搜索数据

c++ - 如何使用友元函数在模板类之外重载运算符==?