views:

44

answers:

2

Is this code not going to produce an error:

_bstr_t text=n.GetText();

 atof((char*)text)

Where text is a double value.

I know that the _bstr_t produces a const char* in the conversion; so I'm not sure if the atof() is going to work?

+2  A: 

First of all, _bstr_t has operator char*() const, so you don't need a cast. Then, this operator calls ConvertBSTRToString() which returns a heap-allocated char array you need to delete[] later (see the example in the linked article), failing to do so will result in a memory leak. Finally, you should be aware that _bstr_t can encapsulate a null pointer which corresponds to an empty string and your program should handle such situations.

sharptooth
But why do the conversion at all? Why not just use `_wtof` on the raw BSTR?
Rup
I don't mind. But checking for the null BSTR is necessary anyway.
sharptooth
I'm pretty sure the _bstr_t class manages the memory with an internal data structure; you should not have to free the memory yourself.
Luke
@Luke: I've looked into the SDK headers and see that it calls ConvertBSTRToString(). YMMV.
sharptooth
@sharptooth: I don't disagree, but that memory is managed via an internal class Data_t. Also, the documentation for the _bstr_t operators don't say anything about freeing the memory. If you free it yourself you will end up double-freeing.@Rup: That is somewhat dangerous as BSTR is not guaranteed to be NULL-terminated and may in fact contain embedded NULLs. In practice, however, _bstr_t is usually used to wrap NULL-terminated strings (and I think it explicitly NULL-terminates, though I'm not 100% positive).
Luke
@Luke you are correct, you usually do not need to manage memory associated with a _bstr_t. (You can call Detach to take ownership of the internal BSTR, but the char* you cannot take ownership of.)
Stephen Nutt
+1  A: 

It seems to me it is absolutely safe to use _wtof(text) (see http://msdn.microsoft.com/en-us/library/hc25t012.aspx) to make the conversion which you need.

@sharptooth: In general BSTR data must not be always zero-terminated string. But corresponds to description of the _bstr_t class (see http://msdn.microsoft.com/en-us/library/zthfhkd6.aspx):

A _bstr_t object encapsulates the BSTR data type. The class manages resource allocation and deallocation through function calls to SysAllocString and SysFreeString and other BSTR APIs when appropriate.

Only data allocated with SysAlloc-functions other as SysAllocString can be not zero-terminated. The function SysAllocString allocate always additional two bytes and fill there with L'\0'. To read more information about this subject I refer to http://blogs.msdn.com/b/ericlippert/archive/2003/09/12/52976.aspx.

Oleg