代码如下所示:
class A
{
public:
std::string name;
};
A a;
CComBSTR textValue;
// some function which fills textValue
a.name = W2A(textValue);
Run Code Online (Sandbox Code Playgroud)
现在,我已经使用了 CComBSTR,因此我不必释放 BString,但是 W2A 是否分配我可能需要处理的任何内存?即我应该有:
char *tmp = W2A(textValue);
a.name = tmp;
// do something to deallocate tmp?
Run Code Online (Sandbox Code Playgroud)
使用 W2A/A2W 宏时要非常小心。它们是通过“alloca”(直接在堆栈上动态分配)实现的。在某些涉及循环/递归/长字符串的情况下,您将得到“ stackoverflow ”(不是开玩笑)。
推荐的方法是使用“新”帮助程序模板。请参见ATL 和 MFC 字符串转换宏
A a;
CComBSTR textValue;
// some function which fills textValue
CW2A pszValue( textValue );
a.name = pszValue;
Run Code Online (Sandbox Code Playgroud)
该转换使用 128 字节的常规“堆栈中”缓冲区。如果它太小,则会自动使用堆。您可以直接使用模板类型来调整权衡
A a;
CComBSTR textValue;
// some function which fills textValue
CW2AEX<32> pszValue( textValue );
a.name = pszValue;
Run Code Online (Sandbox Code Playgroud)
不用担心:您只是减少了堆栈使用量,但如果 32 字节不够,则会使用堆。正如我所说,这是一种权衡。如果您不介意,请使用CW2A.
无论哪种情况,都无需进行清理:-)
请注意,当 pszValue 超出范围时,任何待转换的 char* 都可能指向垃圾。请务必阅读“示例 3 转换宏的错误使用”。以及上面链接中的“关于临时类实例的警告”。
| 归档时间: |
|
| 查看次数: |
4768 次 |
| 最近记录: |