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

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

本文关键字:是否 任何清 string W2A BSTR 转换 std      更新时间:2023-10-16

代码如下所示:

class A 
{
  public:
     std::string name;
};
A a;
CComBSTR textValue;
// some function which fills textValue
a.name = W2A(textValue);

现在,我已经使用了CComBSTR,所以我不必解除BString的锁定,但W2A是否分配了我可能需要处理的内存?即我应该有:

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

使用W2A/A2W宏时要非常小心。它们是用"alloca"(直接在堆栈上进行动态分配)实现的。在某些涉及循环/递归/长字符串的情况下,您将得到一个"stackerflow"(不开玩笑)。

推荐的方法是使用"新"助手模板。请参阅ATL和MFC字符串转换宏

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

转换使用128字节的常规"堆栈内"缓冲区。如果它太小,堆将自动使用。您可以通过直接使用模板类型来调整权衡

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

别担心:您只是减少了堆栈的使用量,但如果32字节还不够,则会使用堆。正如我所说,这是一种权衡。如果您不介意,请使用CW2A

在任何一种情况下,都不需要进行清理:-)

请注意,当pszValue超出范围时,转换的任何挂起的char*都可能指向垃圾。请务必阅读上面链接中的"示例3转换宏的错误使用"answers"关于临时类实例的警告"。

不需要清理,因为W2A在堆栈上分配内存。您必须注意某些与内存相关的陷阱(堆栈分配的直接后果),但在这种特定的情况下,没有任何可疑之处。