c++ - 将 BSTR 存储在 std::vector 中?

标签 c++ stl vector bstr

我有一个 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.

因此,在做出选择之前,请考虑以下事项:

  1. _bstr_t是对 BSTR 的引用计数智能指针包装器而CComBSTR 提供任何引用计数。
  2. _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/

相关文章:

c++ - 通过模板调用可能不存在的成员函数

c++ - 排序 vector 不断修改数据并打印不正确的结果

c++ - 派生类中指向基类的指针 vector

c++ - 无法指定 vector 的初始大小

c++11 - 为什么 std::for_each 迭代器需要一个可复制构造的迭代器

c++ - 使用 vector

c++ - g++ 在终端中,构建有效但没有 a.out

c++ - Lua + SWIG 猴子补丁

c++ - OpenCV 均值函数因从 OpenCV 阈值函数创建的掩码而崩溃?

c++ - 获取 std::vector<std::string>::iterator 的索引