简体   繁体   English

当使用W2A将BSTR转换为std :: string时,是否需要进行清理?

[英]When using W2A to convert BSTR to std::string, is there any clean up needed?

Code looks like the following: 代码如下所示:

class A 
{
  public:
     std::string name;
};

A a;
CComBSTR textValue;
// some function which fills textValue
a.name = W2A(textValue);

Now, I've used CComBSTR so I don't have to dealloc the BString, but does W2A allocate any memory that I might have to deal with? 现在,我已经使用了CComBSTR,所以我不必释放BString,但是W2A是否会分配我可能需要处理的任何内存? ie should I have: 即我应该:

 char *tmp = W2A(textValue);
 a.name = tmp;
 // do something to deallocate tmp?

No cleanup is required because W2A allocates memory on the stack . 不需要清理,因为W2A 在堆栈上分配内存 There are certain memory-related pitfalls you have to be aware of (direct consequences of stack allocation), but nothing that looks immediately suspicious in this specific scenario. 您必须注意某些与内存相关的陷阱(堆栈分配的直接后果),但在此特定方案中没有任何看起来立即可疑的内容。

Be very cautious with the W2A/A2W macros. 对W2A / A2W宏非常谨慎 They are implemented with "alloca" (dynamic allocation directly on the stack). 它们使用“alloca”实现(直接在堆栈上进行动态分配)。 In certain circumstances involving loop/recursion/long string, you will get a " stackoverflow " (no kidding). 在涉及循环/递归/长字符串的某些情况下,您将获得“ stackoverflow ”(不开玩笑)。

The recommanded way is to use the "new" helpers templates. 推荐的方法是使用“新”帮助程序模板。 See ATL and MFC String Conversion Macros 请参阅ATL和MFC字符串转换宏

A a;
CComBSTR textValue;
// some function which fills textValue
CW2A pszValue( textValue );
a.name = pszValue;

The conversion use a regular "in stack" buffer of 128 bytes. 转换使用128字节的常规“堆栈”缓冲区。 If it's to small, the heap is automatically used. 如果它很小,则会自动使用堆。 You can adjust the trade-off by using directly the template types 您可以直接使用模板类型来调整权衡

A a;
CComBSTR textValue;
// some function which fills textValue
CW2AEX<32> pszValue( textValue );
a.name = pszValue;

Don't worry: you just reduced your stack usage, but if 32 bytes is not enough, the heap will be used. 不要担心:您只是减少了堆栈使用量,但如果32个字节不够,则将使用堆。 As I said, it's a trade-off. 正如我所说,这是一个权衡。 If you don't mind, use CW2A . 如果您不介意,请使用CW2A

In either case, no clean up to do:-) 在任何一种情况下,没有清理做:-)

Beware, when pszValue goes out of scope, any pending char* to the conversion may be pointing to junk. 请注意,当pszValue超出范围时,转换的任何挂起的char *都可能指向垃圾。 Be sure to read the "Example 3 Incorrect use of conversion macros." 请务必阅读“示例3转换宏的错误使用”。 and "A Warning Regarding Temporary Class Instances" in the above link. 以上链接中的“关于临时班级实例的警告”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM