当我完成使用后,从堆中分配的内存中删除std :: string的最佳方法是什么?谢谢!如何从内存中正确释放std :: string
29
A
回答
52
std::string
只是一个普通的类,所以通常的规则适用。
如果您将作为全局变量的std::string
对象作为类成员分配......您不需要做任何特殊的事情,当它们超出范围时,调用它的析构函数,并且它将处理释放用于字符串的内存自动。
int MyUselessFunction()
{
std::string mystring="Just a string.";
// ...
return 42;
// no need to do anything, mystring goes out of scope and everything is cleaned up automatically
}
,你必须做一些事情是当你在分配使用new
操作堆的std::string
的唯一情况;在这种情况下,与分配了new
的任何对象一样,您必须致电delete
将其释放。
int MyUselessFunction()
{
// for some reason you feel the need to allocate that string on the heap
std::string * mystring= new std::string("Just a string.");
// ...
// deallocate it - notice that in the real world you'd use a smart pointer
delete mystring;
return 42;
}
如示例中暗示,在总体上是毫无意义的在堆上分配std::string
,并且,当你需要的,还是应该在一个智能指针,以避免甚至冒着内存泄露封装此指针(以例外的情况下,多个返回路径,...)。
其实
std::string
被定义为namespace std { typedef std::basic_string<char> string; };
所以它的
basic_string
模板类char
类型的角色的实例化的同义词(这不回答任何改变,但在你的必须甚至在新手问题上迂腐)。
4
如果它在堆上,则使用delete
,如果它位于堆栈上,则不使用delete
。
5
std::string foo("since it's on the stack, it will auto delete out of scope");
或:
std::string* foo = new std::string("allocated on the heap needs explicit destruction")
delete foo;
1
void foo() {
string* myString = new string("heap-allocated objects are deleted on 'delete myString;'");
cout << *myString << endl;
delete myString;
}
或更好,但避免可能的指针和时使用自动变量:
void foo() {
string myString("stack-allocated string is automatically deleted when myString goes out of scope");
cout << myString << endl;
}
0
只是治疗的std :: string任何基本类型。
std::string *str = new std::string("whatever");
///code
delete str;
相关问题
- 1. 用std :: move()释放内存?
- 2. 我是否正确释放内存?
- 3. 内存未被正确释放?
- 4. Alea的犯规释放内存正确
- 5. 正确的释放内存的方法
- 6. C++ - std :: list remove_if不释放内存?
- 7. 如何正确释放C中分配的内存?
- 8. 如何从iphone中释放presentModalViewController内存?
- 9. 释放std :: vector的内存C++
- 10. 如何正确释放UITabController
- 11. 如何正确释放CGImageRef?
- 12. 如何正确释放AVCaptureSession
- 13. 如何正确释放UIPopoverController?
- 14. 即使我明确释放内存,内存也不会释放
- 15. PtrToStringChars,如何释放内存?
- 16. 如何正确释放分配给链表的内存?
- 17. 如何正确释放与getline()函数相关的内存?
- 18. 我是否正确释放堆中的内存?
- 19. 如何从内存释放对象
- 20. 如何(暂时)从VirtualAlloc释放内存?
- 21. 如何从视图控制器在内存中释放内存
- 22. Informix - 如何释放内存?
- 23. 如何释放gpu内存?
- 24. 如何强制我的std :: map释放使用的内存?
- 25. 如何在-dealloc中正确释放CGMutablePathRef?
- 26. 在C中释放内存的正确方法是什么?#
- 27. 从内存中释放UIWebView内容,强制应用程序释放内存
- 28. C++何时使用delete []并正确释放内存?
- 29. C++中的数组正确分配和释放内存
- 30. 如何在C++中释放内存
与其他任何对象一样。真的,你能澄清你的问题吗?你在做什么,你想要达到什么目标,你尝试了什么,以及它如何工作? – 2011-02-12 18:08:57
你能扩展你的问题吗?在什么情况下? – vz0 2011-02-12 18:09:40