简体   繁体   English

结构对象析构函数

[英]Struct object destructor

If I were to define a struct like so:如果我要定义这样的结构:

struct info{
   std::string name;
}

and create a new instance of said struct on the heap via:并通过以下方式在堆上创建所述结构的新实例:

info* i = new info();

Is the destructor for string called automatically upon calling delete on info, such that any internally allocated memory by the name object is freed?是否在对 info 调用 delete 时自动调用字符串的析构函数,以便释放名称对象的任何内部分配内存? Is this behavior that should be avoided in C++?在 C++ 中应该避免这种行为吗?

Thanks谢谢

Yes, the destructor is called automatically once delete is called for info .是的,一旦为info调用delete就会自动调用析构函数。 But this doesn't mean that all the internal memory will be freed.但这并不意味着所有内部存储器都将被释放。 There are exceptions here.这里也有例外。

Consider a case考虑一个案例

struct info
{
  char *name;
}

and in the main code并在主代码中

int main()
{
  info *n =  new info; 
  n->name = new char;

  delete n;
}

In this case, the memory for name will not be freed and you will have a memory leak.在这种情况下, name的内存将不会被释放,并且您将发生内存泄漏。

As linked in the comments by @Joachim Pileborg正如@Joachim Pileborg的评论中所链接的

Destruction sequence 销毁顺序
For both user-defined or implicitly-defined destructors, after the body of the destructor is executed, the compiler calls the destructors for all non-static non-variant members of the class, in reverse order of declaration , then it calls the destructors of all direct base classes in reverse order of construction (which in turn call the destructors of their members and their base classes, etc), and then, if this object is of most-derived class, it calls the destructors of all virtual bases.对于用户定义或隐式定义的析构函数,在析构函数体执行完毕后,编译器按照声明的相反顺序调用类的所有非静态非变体成员的析构函数,然后调用以相反的构造顺序调用所有直接基类(依次调用其成员及其基类的析构函数等),然后,如果此对象属于最派生类,则调用所有虚拟基类的析构函数。

So to answer your question, yes the destructor for name will be called after the body of the destructor for info is called.因此,要回答您的问题,是的,将在调用info的析构函数的主体之后调用name的析构函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM