gpt4 book ai didi

c++ - 我可以释放传递给 SysAllocString 的内存吗?

转载 作者:可可西里 更新时间:2023-11-01 12:57:47 30 4
gpt4 key购买 nike

当通过堆上的 wchar_t* 使用 SysAllocString 分配新的 BSTR 时,我是否应该释放堆上的原始 wchar_t*?

那么这是正确的方法吗?

wchar_t *hs = new wchar_t[20];
// load some wchar's into hs...
BSTR bs = SysAllocString(hs);
delete[] hs;

我应该在这里调用 delete 来释放内存吗?还是 BSTR 刚刚采用了该内存?

最佳答案

SysAllocString(),来自 documentation , 行为如下:

This function allocates a new string and copies the passed string into it.

所以,是的,一旦您调用了 SysAllocString,您就可以释放原始字符数组,因为数据已被复制到新分配的 BSTR 中。

释放使用 new[] 分配的 wchar_t 字符串的正确方法是使用 delete[]

wchar_t *hs = new wchar_t[20];
...
delete[] hs;

释放 BSTR 的正确方法是使用 SysFreeString() :

BSTR bs = SysAllocString(hs);
...
SysFreeString(bs);

虽然您是 BSTR 的新手,但您应该阅读 Eric's Complete Guide to BSTR Semantics .

关于c++ - 我可以释放传递给 SysAllocString 的内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2677097/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com