[英]C++ Dynamic Memory Allocation - char*
I'm having a problem understanding a part of dynamic memory allocation in C++. 我在理解C ++中动态内存分配的一部分时遇到了问题。
I know its standard practice to do something like this to avoid memory leak: 我知道这样做的标准做法是避免内存泄漏:
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
*pvalue = 29494.99;
delete pvalue;
However, I've seen lots of source code like this and delete
was never used there to free up memory: 但是,我看过很多这样的源代码,并且从不使用
delete
释放内存:
char* text = "something";
So the question is simple: should I use delete
EVERY time I no longer need a char pointer (or ANY other)? 所以问题很简单:我是否应该每次都不再需要char指针(或任何其他指针)时使用
delete
? Or are there some exceptions? 还是有例外?
I've read alot and I'm only getting more confused so I hope somebody can help me. 我读了很多书,但我只会变得更加困惑,所以我希望有人能帮助我。
EDIT : 编辑 :
Thank you for explanation. 谢谢您的解释。 Finally I understand and I can make changes to my source code without worrying!
终于我明白了,我可以对源代码进行更改而不必担心!
You should delete
everything you create with new
, and nothing else. 您应该使用
new
delete
您创建的所有内容,并且别无其他。
char* text = "something";
This does not create something with new
, so you shouldn't delete
it. 这不会使用
new
创建任何内容,因此您不应delete
它。
In fact, that statement doesn't create anything (apart from a pointer) - it sets text
to point to a string that was created when your program started. 实际上,该语句不会创建任何内容 (除了指针之外),而是将
text
设置为指向程序启动时创建的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.