In the snippet bellow (simplified scenario of a loop)
_bstr_t original(OLESTR("MyString")); // ref-count = 1
_bstr_t another;
another = original; // ref-count = 2
// do something with another
another.Assign(NULL); // expected: ref-count = 1, and another = NULL
// reset another to NULL before doing other operations
What I expect after another.Assign(NULL)
is:
SysFreeString()
is NOT calledanother
is set to NULL
original
has ref count=1
with existing BSTR
content.What happened:
SysFreeString()
is called for underlying BSTR
of both another
and original
another
is set to NULL
original
remains 2 another.Assign(NULL)
seems to deallocate the underlying BSTR
for both original
and another
.
We had unexpected crash because during coding I thought _bstr_t::Assign()
will decrement the ref count instead of straight away deallocating the BSTR
.
How do I properly reset another
to NULL
without affecting original
?
Please find bellow implementation of Assign
from VC++ 6
.
// assignment operator copies internal data and increases reference count
inline _bstr_t& _bstr_t::operator=(const _bstr_t& s) throw()
{
const_cast<_bstr_t*>(&s)->_AddRef();
_Free();
m_Data = s.m_Data;
return *this;
}
// but _bstr_t::Assign() calls _bstr_t::Data_t::Assign()
// without touching ref count
inline void _bstr_t::Assign(BSTR s) throw(_com_error)
{
if (m_Data != NULL) {
m_Data->Assign(s);
}
else {
m_Data = new Data_t(s, TRUE);
if (m_Data == NULL) {
_com_issue_error(E_OUTOFMEMORY);
}
}
}
// it calls _bstr_t::Data_t::_Free() instead of _bstr_t::_Free() !
inline void _bstr_t::Data_t::Assign(BSTR s) throw(_com_error)
{
_Free();
if (s != NULL) {
m_wstr = ::SysAllocStringByteLen(reinterpret_cast<char*>(s),
::SysStringByteLen(s));
}
}
// this _Free() straight away deallocates the BSTR!
inline void _bstr_t::Data_t::_Free() throw()
{
if (m_wstr != NULL) {
::SysFreeString(m_wstr);
}
if (m_str != NULL) {
delete [] m_str;
}
}
// properly decrements ref count
inline void _bstr_t::_Free() throw()
{
if (m_Data != NULL) {
m_Data->Release();
m_Data = NULL;
}
}
The implementation of _bstr_t::Assign()
has been updated as mentioned by Igor Tandetnik in his comment.
Here's the implementation in VS2010 and it works as expected:
inline void _bstr_t::Assign(BSTR s)
{
_COM_ASSERT(s == NULL || m_Data == NULL || m_Data->GetWString() != s);
if (s == NULL || m_Data == NULL || m_Data->GetWString() != s)
{
_Free();
m_Data = new Data_t(s, TRUE);
if (m_Data == NULL) {
_com_issue_error(E_OUTOFMEMORY);
}
}
}