为什么 wstring::c_str 如果没有正确删除不会导致内存泄漏
代码段 1:
wchar_t *aString()
{
wchar_t *str = new wchar[5];
wcscpy(str, "asdf\0");
return str;
}
wchar_t *value1 = aString();
代码段 2
wstring wstr = L"a value";
wchar_t *value = wstr.c_str();
如果代码段 2 中的值未被删除,则不会发生内存泄漏。但是,如果代码段 1 中的 value1 未被删除,则会出现内存泄漏。 wstring::c_str 的内部代码对我来说看起来是一样的。
Code Segment 1:
wchar_t *aString()
{
wchar_t *str = new wchar[5];
wcscpy(str, "asdf\0");
return str;
}
wchar_t *value1 = aString();
Code Segment 2
wstring wstr = L"a value";
wchar_t *value = wstr.c_str();
If value from code segment 2 is not deleted then an memory leak does not occur. However, if value1 from code segment 1 is not deleted there is a memory leak. The internal code to wstring::c_str looks the same to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一条重要规则:您必须对
new
创建的任何内容使用delete
,并且不能删除其他任何内容。wstr.c_str()
返回一个指向由wstring
对象管理的缓冲区的指针。当字符串被销毁时,它将被释放,之后指针将不再有效。对此使用delete
是错误的。如果修改字符串,指针也会失效。aString()
返回一个指向使用new[]
创建的缓冲区的指针,因此您必须在使用完它后将其删除(使用delete[ ]
,以匹配new[]
)。这很容易出错,这就是为什么最好使用资源管理类(例如string
、wstring
、容器和智能指针)而不是传递原始指针并希望他们得到正确对待。An important rule: you must use
delete
on anything that was created bynew
, and you mustn't delete anything else.wstr.c_str()
returns a pointer to a buffer that's managed by thewstring
object. It will be deallocated when the string is destroyed, after which the pointer will no longer be valid. Usingdelete
on this is wrong. The pointer will also be invalidated if you modify the string.aString()
returns a pointer to a buffer that was created usingnew[]
, so you must delete it when you've finished with it (usingdelete[]
, to matchnew[]
). This is error-prone, which is why it is better practice to use resource-managing classes (likestring
,wstring
, containers and smart pointers) rather than passing around raw pointers and hoping they are treated correctly.因为
c_str()
返回一个指向wstring
内部表示的指针。该类对其包含的数据保持控制。Because
c_str()
returns you a pointer to the internal representation of thewstring
. The class keeps control of the data it contains.取自
basic_string::c_str()
来自 MSDN 的文档:Taken from the
basic_string::c_str()
documentation from MSDN:我要冒险说 wstring 不是 wchar_t,而是一个具有返回 wchar_t * 的运算符的类,因此在 wstring 的析构函数中,它可能会释放自己的 wchar_t 副本* 它返回。
I'm going to go out on a limb and say that a wstring is not a wchar_t, but instead a class that has an operator to return a wchar_t *, so in the destructor of wstring, it likely frees its own copy of the wchar_t * it returns.