删除类对象数组?

发布于 2024-11-06 12:29:43 字数 385 浏览 0 评论 0原文

几乎众所周知,下面的代码正确地释放了 100 个整数的内存。

int* ip = new int[100];
delete [] ip; 

我认为即使对于用户定义的类它也有效:

Node* ip = new Node[100];
delete [] ip; 
  1. 在第一种情况下,要释放的内存大小(400 字节)是在编译时确定的吗?基本上,内部发生了什么?

  2. 在第二种情况下,Node 的析构函数会在 100 个对象中的每一个上调用吗?

本质上,我一直在使用这种语法,但从未理解内部发生了什么,现在我很好奇。

It's almost common knowledge that the code below correctly frees the memory of 100 integers.

int* ip = new int[100];
delete [] ip; 

And I think even for user defined classes it works:

Node* ip = new Node[100];
delete [] ip; 
  1. In the first case, is the size of memory to be freed (400 bytes), determined at compile time? Basically, what goes on internally?

  2. In the second case, will the destructor of Node be called on each of the 100 objects?

Essentially, I have been using this syntax, but never understood what goes on internally and now I am curious.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

呆萌少年 2024-11-13 12:29:43
  1. 不会。内存分配器会无形地跟踪大小。大小无法在编译时确定,因为这样分配就不是真正动态的,并且以下内容将不起作用:
size_t n;
std::cin >> n;
a = new int[n];
// do something interesting
delete[] a;
  1. 是的。要让自己相信这个事实,请尝试
struct Foo {
    ~Foo() { std::cout << "Goodbye, cruel world.\n"; }
};

// in main
size_t n;
std::cin >> n;
Foo *a = new Foo[n];
delete[] a;
  1. No. The memory allocator invisibly keeps track of the size. The size cannot be determined at compile time, because then the allocation would not be truly dynamic and the following would not work:

size_t n;
std::cin >> n;
a = new int[n];
// do something interesting
delete[] a;
  1. Yes. To convince yourself of this fact, try

struct Foo {
    ~Foo() { std::cout << "Goodbye, cruel world.\n"; }
};

// in main
size_t n;
std::cin >> n;
Foo *a = new Foo[n];
delete[] a;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文