windows 我可以释放传递给 SysAllocString 的内存吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2677097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I free memory passed to SysAllocString?
提问by noctonura
When allocating a new BSTR with SysAllocString via a wchar_t* on the heap, should I then free the original wchar_t* on the heap?
当通过堆上的 wchar_t* 分配带有 SysAllocString 的新 BSTR 时,我应该释放堆上的原始 wchar_t* 吗?
So is this the right way?
那么这是正确的方法吗?
wchar_t *hs = new wchar_t[20];
// load some wchar's into hs...
BSTR bs = SysAllocString(hs);
delete[] hs;
Am I supposed to call delete here to free up the memory? Or was that memory just adoped by the BSTR?
我应该在这里调用 delete 来释放内存吗?或者那个记忆只是被 BSTR 掺杂了?
回答by i_am_jorf
SysAllocString(), from the documentation, behaves like this:
SysAllocString(),来自文档,其行为如下:
This function allocates a new string and copies the passed string into it.
此函数分配一个新字符串并将传递的字符串复制到其中。
So, yes, once you've called SysAllocString you can free your original character array, as the data has been copied into the newly allocated BSTR.
所以,是的,一旦您调用了 SysAllocString,您就可以释放原始字符数组,因为数据已被复制到新分配的 BSTR 中。
The proper way to free a string of wchar_t
allocated with new[]
is to use delete[]
.
释放wchar_t
分配的字符串的正确方法new[]
是使用delete[]
.
wchar_t *hs = new wchar_t[20];
...
delete[] hs;
The proper way to free a BSTR
is with SysFreeString():
释放 a 的正确方法BSTR
是使用SysFreeString():
BSTR bs = SysAllocString(hs);
...
SysFreeString(bs);
While you're new to BSTRs, you should read Eric's Complete Guide to BSTR Semantics.
当您不熟悉 BSTR 时,您应该阅读Eric 的 BSTR 语义完整指南。
回答by éric Malenfant
As its name implies, SysAllocString
allocates its memory, it does not "adopt" its argument's memory. BSTRs are size-prefixed andnull-terminated, so "adopting" a c-style string is impossible, as there is no space for the size prefix.
顾名思义,SysAllocString
分配其内存,而不是“采用”其参数的内存。BSTR 是大小前缀和空终止的,因此“采用”c 样式字符串是不可能的,因为大小前缀没有空间。
回答by Michael Burr
The docs for SysAllocString()
are pretty clear:
的文档SysAllocString()
非常清楚:
This function allocates a new string and copies the passed string into it.
此函数分配一个新字符串并将传递的字符串复制到其中。
The string data you pass in is copied - SysAllocString()
doesn't use it after it's completed - you're free to deallocate or modify that buffer.
您传入的字符串数据被复制 -SysAllocString()
完成后不使用它 - 您可以自由释放或修改该缓冲区。
回答by John Dibling
Yes, delete
the memory.
是的,delete
记忆。