基本类型动态分配数组的析构函数?

发布于 2025-01-03 03:18:40 字数 335 浏览 0 评论 0原文

如果我想删除动态分配的基本类型值数组:

int *it = new int[10]

我是否只需将 delete [] it 放在析构函数中即可关心正确释放内存吗?

或者

意识到,由于指针是原始类型,删除动态分配的数组是否涉及在析构函数中执行类似的操作:

for (size_t idx = 0; idx != 5; ++idx)
        delete sp[idx];
    delete[] sp;

我对此感到相当困惑,因为我的程序中有很多与内存相关的错误。

If I want to delete a dynamically allocated array of primitive type values:

int *it = new int[10]

do I just put delete [] it in the destructor to take care of releasing memory properly?

OR

Realizing that, as a pointer is a primitive type, does deleting a dynamically allocated array involve doing something like this in the destructor:

for (size_t idx = 0; idx != 5; ++idx)
        delete sp[idx];
    delete[] sp;

I'm rather confused about this as I am having a lot of memory related errors in my program.

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

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

发布评论

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

评论(2

凉月流沐 2025-01-10 03:18:40

如果您有:

int* it = new int[10];

删除的正确方法是:

delete[] it;

如果您有这种类型的成员变量,您需要实现复制构造函数和赋值运算符,因为它们的默认版本是不够的,或者会使类不可复制。

由于这是 C++,我建议使用 std::vector 来代替,因为这将为您处理内存管理。

If you have:

int* it = new int[10];

the correct way to delete it is:

delete[] it;

If you have a member variable of this type you need to implement a copy constructor and assignment operator as the default versions of these are not sufficient or make the class uncopyable.

As this is C++ I would suggest using std::vector<int> instead as this will handle the memory management for you.

弱骨蛰伏 2025-01-10 03:18:40

如果您要使用 newdelete,则要遵循的一般规则是:使用与您使用的 delete 一样多的 >新的

在您的例子中,您仅调用了一次 new[] 。您应该仅删除一次delete[]

顺便说一句,如果您曾经在成员变量中存储指针,请考虑 三法则

我说“如果您要使用 newdelete”,因为您通常不应该这样做。使用 RAII 技术和标准容器,完全有可能编写完全有用的程序,而不会直接调用 newdelete

如果您尝试维护 int 数组,请使用 std::vector

class MyClass {
    std::vector<int> it;

    void SomeFun() { it.resize(10); }
};

然后,在您的析构函数中,不执行任何操作。向量会在你根本不需要帮助的情况下消失。

If you are going to use new and delete, the general rule to follow is this: Use exactly as many deletes as you did news.

In your case, you invoked new[] only once. You should inovke delete[] only once.

As an aside, if you ever store a pointer in a member variable, please consider the Rule of Three.

I say "If you are going to use new and delete", because you often shouldn't. Using RAII techniques, and standard containers, it is entirely possible to write perfectly useful programs that never directly invoke new or delete.

If you are trying to maintain an array of ints, use std::vector:

class MyClass {
    std::vector<int> it;

    void SomeFun() { it.resize(10); }
};

Then, in your destructor, do nothing. Vectors disappear with no help from you at all.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文