java动态删除对象_使用delete关键字删除具有动态分配块的对象是否安全

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-1 09:47   56   0

如果您有这样的事情:

class Foo

{

public:

int* block;

Foo()

{

block = new int[10];

}

private:

Foo(const Foo&);

Foo& operator =(const Foo&);

};

然后这样做:

Foo* foo = new Foo;

delete foo;

然后是的,你是在泄漏记忆 . 永远不会释放Foo对象中的动态块 . 您可以使用释放它的析构函数来解决这个问题 . (源代码,您还需要在类声明中声明析构函数):

Foo::~Foo()

{

delete [] block;

}

我建议你做两件事

计算删除's and the new' . 如果它们不相同,那通常是一个问题 .

在#2之后,btw,可能会给你一个看起来类似于此的对象:

class Foo

{

public:

std::array block;

Foo() // note: default-construction of `block`

{

}

// note: default *destructor* will clean up member variables

// by firing their destructors for you. in this case the destructor

// for our 'block' member is a std::array that knows how to self-clean.

// note: we no longer have to hide or implement copy construction and

// assignment operator functionality. The default implementation of

// these properly member-copy and member-assign respectively.

};

一个用法(许多可能性之一),如下所示:

std::unique_ptr foo(new Foo);

请看最后一个例子的来源中的注释 . 通过使用练习自我管理成员的课程,你的记忆管理肩负着巨大的压力 . 在提升重量的同时,也有可能引入与其相关的错误,例如内存泄漏,浅拷贝危险等 .

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP