使用后需要删除CString来释放内存吗? [英] Need to delete CString after use to free memory?

查看:561
本文介绍了使用后需要删除CString来释放内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用这样的CString:

If I am using a CString like this:

void myFunc(char *str)
{
  CString s(str);
  // Manipulate other data with CString
  // ...
  // Finished

  // Should I somehow delete 's' here to avoid a memory leak?
}

函数超出范围后是否会删除字符串?

Is the string erased once the function goes out of scope?

此外,如果我构造的对象没有 new <,我也知道 new 关键字会分配内存。 / code>关键字,是否仍在分配内存?我的直觉告诉我是的,但我想验证一下。

Also, I know that the new keyword allocates memory, if I construct an object without the new keyword, is memory still allocated? My intuition tells me yes, but I would like to verify.

例如

CString *asdf = new CString("ASDF");
// same as?
CString asdf("ASDF"); 


推荐答案

上分配内存,因此

CString *asdf = new CString("ASDF");

在堆上分配 CString 并分配指向 asdf 的指针。除非您调用 delete asdf ,否则不会释放该内存,也不会调用 asdf 的析构函数。

Allocates a CString on the heap and assigns a pointer to it to asdf. That memory will not be freed, nor will the destructor of asdf be called until you call delete asdf.

没有 new ,您将在堆栈上进行分配,因此

Without new, you are allocating on the stack, so

CString asdf("ASDF");

分配堆栈内存, asdf 表示。取消堆栈堆栈时(如从函数返回时),将自动回收此内存,并且当超出范围时,将自动调用 asdf 的析构函数。

allocates stack memory, which asdf represents. This memory is automatically reclaimed when the stack is unwound (as in when you return from a function) and the destructor of asdf is automatically called when it goes out of scope.

此外, CString 会清理自己的资源,因此如果 CString 对象被清除(如果它在堆栈上,则超出范围;如果在堆上,则被删除),其使用的资源也将被清除。

Also, CString cleans up its own resources, so if the CString object is cleaned up (goes out of scope if it's on the stack or is deleted if it's on the heap), the resources it uses will also be cleaned up.

这篇关于使用后需要删除CString来释放内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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