Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_bstr_t to char*, amazing result

Tags:

char

bstr

first:

LPCTSTR asdfsdf = (LPCTSTR)(_bstr_t)v;
printf("%s\n", asdfsdf);

second:

printf("%s\n", (LPCTSTR)(_bstr_t)v);

they are the same, but the first condition causes unreadable code

why?

like image 669
Janli Lee Avatar asked Dec 06 '12 07:12

Janli Lee


1 Answers

The _bstr_t class encapsulates a BSTR inside a C++ class. In your first instance:

LPCTSTR asdfsdf = (LPCTSTR)(_bstr_t)v;

you are creating a _bstr_t object, extracting the LPCTSTR out of it, but then the temporary _bstr_t object gets destructed. Whatever asdfsdf pointed to is now deallocated and can no longer be used.

In your second example

printf("%s\n", (LPCTSTR)(_bstr_t)v);

the temporary _bstr_t object is not destructed until after the printf() is called, so there is no problem using the LPCTSTR value.

like image 180
Greg Hewgill Avatar answered Nov 07 '22 03:11

Greg Hewgill