Need to delete CString after use to free memory?(使用后需要删除 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 关键字的对象,内存仍然分配吗?我的直觉告诉我是的,但我想验证一下.
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");
推荐答案
new 在 heap 上分配内存,所以
new allocates memory on the heap, so
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,你在stack上进行分配,所以
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 以释放内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用后需要删除 CString 以释放内存吗?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
