【问题标题】:why does &(std::to_wstring()) return an empty string?为什么 and(std::to_string()) 返回一个空字符串?
【发布时间】:2014-02-26 02:23:24
【问题描述】:

我正在尝试在 Windows 的 C++/CX 应用程序中使用 std::to_wstring 函数将 int 转换为 wstring*

以下内容不起作用:

wstring* turn = &(to_wstring(50));               //the value of *turn is ""

但是这样做:

wstring tu = to_wstring(50);
wstring* turn = &tu;                             //the value of *turn is "50"

有人能解释一下为什么吗?两个代码 sn-ps 不应该显示完全相同的行为吗?

【问题讨论】:

  • 第一个甚至不应该编译,但它是一个 Visual C++ 错误

标签: c++ windows-runtime


【解决方案1】:

to_wstring(50) 是临时的。临时变量在完整表达式的末尾被销毁(,就在分号之后)。所以在第一次 sn-p 运行后,turn 指向的内存不再包含有效的std::wstring,因为它已经被销毁了。

在第二个 sn-p 中,临时 to_wstring(50)复制到变量 tu 中。临时对象已销毁,但 tu 未销毁,因为它仍在范围内。

【讨论】:

  • 好像很有道理,非常感谢!
猜你喜欢
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
  • 2013-10-22
  • 2021-10-09
相关资源
最近更新 更多