What's the difference between BSTR and _bstr_t?

前提是你 提交于 2019-12-18 10:53:05

问题


Can anyone explain the difference between the types mentioned above and some sample usage to clearly explain the difference between the two?

Any help would be highly appreciated! Note: this question is a spin-off from this other question


回答1:


BSTR is the string data type used with COM.

_bstr_t is a wrapper class that works like a smart pointer, so it will free the allocated memory when the variable is destroyed or goes out of scope. _bstr_t also has reference counting, which increases every time you pass the _bstr_t variable by value (avoiding unnecessary copy) and decrement when it is no longer used. Whenever all references are destroyed, the allocated memory for the string is freed.

An alternative to BSTR is the CComBSTR. It also manages the memory for the BSTR, but has no reference counting.




回答2:


BSTR is a raw pointer, while _bstr_t is a class encapsulating that pointer.

It's the same difference as char* vs. std::string.




回答3:


_bstr_t wraps the BSTR type. So, when you instantiate a _bstr_t, you are also creating BSTR. _bstr_t simply wraps everything up for you and acts sort of like a "smart ptr" to the BSTR.

BSTR

http://msdn.microsoft.com/en-us/library/ms221069.aspx

SysAllocString()

http://msdn.microsoft.com/en-us/library/ms891285.aspx

_bstr_t

https://msdn.microsoft.com/en-us/library/zthfhkd6.aspx



来源:https://stackoverflow.com/questions/341462/whats-the-difference-between-bstr-and-bstr-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!