c++ - 为什么使用这两组语句时variable中的数据不同?

标签 c++ visual-c++

当我尝试通过访问类型转换函数的结果(包括括号)来获取 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/

相关文章:

c++ - 链接失败。如何使用 'NtQuerySystemTime' windows函数?

c++ - 何时使用指针,何时不使用它们

c++ - VC++ 注释、文档和 IntelliSense

c++ - 错误 C2664 : in c++?

visual-studio - 在 Visual Studio 中恢复对 UI 的更改

C++ |只有引用变量在函数模板中起作用

java - getter 和 setter 会影响 C++/D/Java 中的性能吗?

c++ - 导入 ctype;在 C++ 应用程序中嵌入 python

visual-c++ - 使用串行设备控制应用程序卷

C++:编译某些代码所需的前向类定义