-Error reading characters of string

后端 未结 2 975
执念已碎
执念已碎 2021-01-05 05:56

I have the following block of code:

for( CarsPool::CarRecord &record : recs->GetRecords())
{
  LVITEM item;
  item.mask = LVIF_TEXT;
  item.cchTextMax         


        
2条回答
  •  借酒劲吻你
    2021-01-05 06:42

    getCarName likely returns a temporary. After the assignment the temporary object is destroyed and the pointer item.pszText points to invalid memory. You must ensure that the string object is valid during the call to ListView_InsertItem.

    std::string text(record.getCarName());
    item.iSubItem = 0;
    item.pszText = const_cast(text.c_str());
    item.iItem = 0;
    ListView_InsertItem(CarsListView, &item);
    

    The const_cast is an artifact of the fact that the Windows API uses the same structure to set and retrieve information. When invoking ListView_InsertItem the structure is immutable, however there is no way to reflect that in the language.

提交回复
热议问题