C ++内存管理:谁负责 [英] C++ Memory Management: Who is responsible

查看:58
本文介绍了C ++内存管理:谁负责的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在编写一个C ++类.该类具有以下字段:

Suppose I am writing a C++ class. The class has the following fields:

  • 一个整数.
  • 一个C ++字符串
  • 可动态调整大小的整数数组及其指向的指针.

在析构函数中,我知道我必须通过调用 new 删除我早先声明的任何内容.在这种情况下,我知道我必须释放用于int数组的空间.字符串的内存呢?我知道我不负责释放其内存,因为我没有调用 new 进行分配,但是如何释放它呢?C ++何时调用其析构函数?

In the destructor, I know I have to delete anything that I had earlier claimed by calling new. In this case, I know I have to free the space I used for the int array. What about the string's memory? I know I'm not responsible for releasing its memory, because I didn't call new to allocate it, but how does it get freed? When does C++ call its destructor?

推荐答案

字符串的内存如何?我知道我不负责释放它的内存,因为我没有调用new来分配它,但是如何释放它呢?

What about the string's memory? I know I'm not responsible for releasing its memory, because I didn't call new to allocate it, but how does it get freed?

您的类的析构函数隐式调用 std :: string 的析构函数,该析构函数进而处理其自身资源的释放.没什么可担心的.

Your class's destructor implicitly calls std::string's destructor which in turn handles the freeing of its own resources. Nothing else to worry.

C ++何时调用其析构函数?

When does C++ call its destructor?

当调用类的对象的析构函数时.这意味着当该对象超出范围或由 new 创建该对象时,在指向该对象的指针上调用了 delete .

When your class' object's destructor is called. That means when that object goes out of scope or delete has been called on a pointer to it when it has been created by new.

我以某种方式了解您的问题.您可能会认为 new 递归 new 是您的类的成员.不.它不是那样的.除非您的类本身对成员变量执行 new ,否则您将需要对其进行调用 delete .

I somehow understand your problem. You may think that new recursively news the members of your class. No. It doesn't do it that way. Unless your class itself does new on the member variables will you need to call delete on them.

这篇关于C ++内存管理:谁负责的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆