当我尝试通过访问类型转换函数的结果(包括括号)来获取 c_str 时,字符串为空。
const wchar_t* test1 = (type_conversion.string_to_wstring(result1)).c_str();
// test1 contains empty string "";
当我使用中间变量“testWstring”时,结果是不同的 - 正如我所期望的那样,我得到了最初在“result1”中的内容。
wstring testWstring = type_conversion.string_to_wstring(result1);
const wchar_t* test1 = testWstring.c_str();
// test1 contains "hi";
typeConversion.string_to_wstring 函数如下所示:
wstring type_conversion::string_to_wstring(const string& str)
{
int len;
int slength = (int) str.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}
我显然误解了这里的一些东西。来自 C# 背景,我希望这两组语句在“test1”中产生相同的值。
为什么不是这样?
最佳答案
调用 string_to_wstring 的结果未绑定(bind)到引用或分配给对象。它在完整表达式的末尾被破坏。另见 sequence-point .
在第二个示例中,您将结果分配给一个保留在作用域中的变量。
关于c++ - 为什么使用这两组语句时variable中的数据不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23138966/