我有一个 ATL COM 组件方法,它将 BSTR 作为输入参数。我需要在数组中添加对此方法的每次调用。我不能使用 SAFEARRAY,因为它是固定大小的,所以我认为 std::vector 是最简单的选择。当然,每次添加 vector 时我都需要调用 SysAllocString。这意味着在 vector 被销毁之前,需要为每个条目调用 SysFreeString。
我一直在寻找一个更简单/更清洁的解决方案,并考虑将 vector 声明为 vector<_bstr_t> ,这将包括自动清理。然而,在我的脑海深处,有一些事情正在对在标准容器中保存实际上是智能指针的东西发出警报。我的担心是否合理,或者我可以安全地这样做吗?如果没有,还有其他更好的解决方案吗?
最佳答案
[regarding
vector< _bstr_t >
] Are my worries justified or can I safely do this?
是的。虽然您可以安全地使用 _bstr_t
请记住,它不仅是一个智能指针,而且还是一个引用计数智能指针。这意味着额外费用。
If not are there any other nicer solutions?
我通常会使用 CComBSTR
而不是 BSTR
或 _bstr_t
.如果您需要引用计数,那么您必须求助于 _bstr_t
.例如:如果您还使用 ATL,您可能只需要 CComBSTR
The CComBSTR class is a wrapper for BSTRs, which are length-prefixed strings. The length is stored as an integer at the memory location preceding the data in the string.
A BSTR is null-terminated after the last counted character but may also contain null characters embedded within the string. The string length is determined by the character count, not the first null character.
因此,在做出选择之前,请考虑以下事项:
-
_bstr_t
是对BSTR
的引用计数智能指针包装器而CComBSTR
不提供任何引用计数。 -
_bstr_t
不重新定义运算符的地址,因此可以安全地存储在 STL 容器中。与CComBSTR
你需要使用CAdapt
.
关于 CAdapt
对象:
CAdapt is a simple template used to wrap classes that redefine the address-of operator (operator &) to return something other than the address of the object. Examples of such classes include ATL's CComBSTR, CComPtr, and CComQIPtr classes, and the compiler COM support class, _com_ptr_t. These classes all redefine the address-of operator to return the address of one of their data members (a BSTR in the case of CComBSTR, and an interface pointer in the case of the other classes).
然后你可以使用:
typedef std::vector< CAdapt< CComBSTR > > MyString;
关于c++ - 将 BSTR 存储在 std::vector 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11102426/