基本类型动态分配数组的析构函数?
如果我想删除动态分配的基本类型值数组:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您有:
删除
的正确方法是:如果您有这种类型的成员变量,您需要实现复制构造函数和赋值运算符,因为它们的默认版本是不够的,或者会使类不可复制。
由于这是 C++,我建议使用
std::vector
来代替,因为这将为您处理内存管理。If you have:
the correct way to
delete
it is: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.如果您要使用
new
和delete
,则要遵循的一般规则是:使用与您使用的delete
一样多的>新的
。在您的例子中,您仅调用了一次 new[] 。您应该仅删除一次
delete[]
。顺便说一句,如果您曾经在成员变量中存储指针,请考虑 三法则。
我说“如果您要使用
new
和delete
”,因为您通常不应该这样做。使用 RAII 技术和标准容器,完全有可能编写完全有用的程序,而不会直接调用new
或delete
。如果您尝试维护
int
数组,请使用std::vector
:然后,在您的析构函数中,不执行任何操作。向量会在你根本不需要帮助的情况下消失。
If you are going to use
new
anddelete
, the general rule to follow is this: Use exactly as manydelete
s as you didnew
s.In your case, you invoked
new[]
only once. You should inovkedelete[]
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
anddelete
", because you often shouldn't. Using RAII techniques, and standard containers, it is entirely possible to write perfectly useful programs that never directly invokenew
ordelete
.If you are trying to maintain an array of
int
s, usestd::vector
:Then, in your destructor, do nothing. Vectors disappear with no help from you at all.