读取字符串字符时出错

读取字符串字符时出错

本文介绍了-读取字符串字符时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码块:

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调试器的信息在这里:

The information from Visual Studio Debugger is here:

为什么程序不能从字符串中读取字符?

Why isn't the program able to read the characters from string?

一个测试表明,它可以这种方式工作:

A test has shown me that it works in this way:

MessageBox(hWnd, (LPSTR)(record.getCarName().c_str()), "Test", MB_OK);

推荐答案

getCarName 可能返回一个临时值.分配后,临时对象被销毁,指针 item.pszText 指向无效的内存.您必须确保在调用 ListView_InsertItem 的过程中字符串对象有效.

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<LPSTR>(text.c_str());
item.iItem = 0;
ListView_InsertItem(CarsListView, &item);

const_cast 是Windows API使用相同的结构来设置和检索信息的事实的产物.调用 ListView_InsertItem 时,该结构是不可变的,但是无法在语言中反映出来.

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.

这篇关于-读取字符串字符时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 21:00