结构对象析构函数

Struct object destructor

如果我像这样定义一个结构:

struct info{
   std::string name;
}

并通过以下方式在堆上创建所述结构的新实例:

info* i = new info();

string 的析构函数是否在调用 info 上的 delete 时自动调用,以便释放名称对象的任何内部分配内存?这种行为应该在 C++ 中避免吗?

谢谢

@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.

所以回答你的问题,是的,name 的析构函数将在 info 的析构函数主体被调用之后被调用。

是的,一旦 deleteinfo 调用,析构函数就会自动调用。但这并不意味着所有的内部存储器都将被释放。这里也有例外。

考虑一个案例

struct info
{
  char *name;
}

在主代码中

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

  delete n;
}

在这种情况下,name 的内存将不会被释放,您将发生内存泄漏。