我有以下代码块:
for( CarsPool::CarRecord &record : recs->GetRecords())
{
LVITEM item;
item.mask = LVIF_TEXT;
item.cchTextMax = 6;
item.iSubItem = 0;
item.pszText = (LPSTR)(record.getCarName().c_str()); //breakpoint on this line.
item.iItem = 0;
ListView_InsertItem(CarsListView, &item);
item.iSubItem = 1;
item.pszText = TEXT("Available");
ListView_SetItem(CarsListView, &item);
item.iSubItem = 2;
item.pszText = (LPSTR)CarsPool::EncodeCarType(record.getCarType());
ListView_SetItem(CarsListView, &item);
}
来自 Visual Studio 调试器的信息如下:
![enter image description here](https://i.stack.imgur.com/a23Uu.png)
为什么程序无法从字符串中读取字符?
测试表明它是这样工作的:
MessageBox(hWnd, (LPSTR)(record.getCarName().c_str()), "Test", MB_OK);
getCarName
可能会返回一个临时的。赋值后,临时对象被销毁,指针item.pszText
指向无效内存。您必须确保字符串对象在调用期间有效ListView_InsertItem
.
std::string text(record.getCarName());
item.iSubItem = 0;
item.pszText = const_cast<LPSTR>(text.c_str());
item.iItem = 0;
ListView_InsertItem(CarsListView, &item);
The const_cast
这是 Windows API 使用相同结构来设置和检索信息这一事实的产物。调用时ListView_InsertItem
结构是不可变的,但是无法在语言中反映这一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)