当使用W2A将BSTR转换为std::string时,是否需要进行任何清理
When using W2A to convert BSTR to std::string, is there any clean up needed?
代码如下所示:
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
在堆栈上分配内存。您必须注意某些与内存相关的陷阱(堆栈分配的直接后果),但在这种特定的情况下,没有任何可疑之处。
相关文章:
- 是否有任何C++功能可以对地图进行排序?
- 在C++行尾写一个分号或多个分号是否会改变任何内容
- C++类型特征,以查看是否可以<uint32_t>对类型"K"的任何变量调用"static_cast(k)"
- 是否有任何建议来统一函数类型限定符并简化可恶的函数类型?
- GoogleMock是否仍然打算与任何测试框架一起使用?
- C++中是否有任何函数等同于python中字典的get函数?
- 用于检查值是否为其任何参数的帮助程序函数
- 在实践中,在运行时为零的乘法中是否有任何"lazy"评估
- MPI:检查是否有任何进程已终止
- 如何检测除整数以外的任何内容是否传递给我的类构造函数?
- C++ 移动语义是否在任何情况下都能节省资源?
- 在调用其析构函数之前,是否有任何实际理由检查某些东西是否可破坏?
- c++ 编译器是否保护常量内存地址免受任何更改?
- 对于堆上的页面对齐内存分配是否有任何优化或不同的 API?
- 使用 std::addressof(std::cout) 而不是 &std::cout 是否有任何风险?
- 是否有任何区域设置会影响宽字符编码?
- 是否使用示波器队列:: swap违反任何规则来清空std ::队列
- 两个线程之间是否存在任何内存泄漏(缓冲、清空)
- 在这种情况下,我是否需要清空映射的内容以避免内存泄漏
- std::getline()是否完全清空缓冲区?