A question on ListView_SetItemText macro for setting text of items in ListView Wi开发者_如何学编程ndows control. Why does the following code works (in a sense that the text is displayed in the ListView)
std::string strNumber = NumberToString(number);
ListView_SetItemText( hListView, iItemIndex, iSubitemIndex, (LPSTR)strNumber.c_str() );
while a direct call doesn't
ListView_SetItemText( hListView, iItemIndex, iSubitemIndex, (LPSTR)NumberToString(number).c_str() );
where
std::string NumberToString ( double Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
Many thanks
Here's the macro definition (in commctrl.h
):
#define ListView_SetItemText(w,i,iS,s) \
{ \
LV_ITEM _lvi;\
_lvi.iSubItem=iS;\
_lvi.pszText=s;\
SNDMSG((w),LVM_SETITEMTEXT,i,(LPARAM)(LV_ITEM*)&_lvi);\
}
This expands to:
...
_lvi.pszText=(LPSTR)NumberToString(number).c_str();
SNDMSG((hListView),LVM_SETITEMTEXT,iItemIndex,(LPARAM)(LV_ITEM*)&_lvi);
}
The NumberToString
function returns a temporary std::string
, which is deleted before the SNDMSG
call. So _lvi.pszText
points to thin air. (Your code would be perfectly safe if ListView_SetItemText
were a genuine function call.)
The first call you send in the pointer to the variable strNumber.
In the second call you send in the pointer to the returned value of the function which is undefined after call.
精彩评论