【问题标题】:What's the life time of the string object passed into std::runtime_error's ctor?传递给 std::runtime_error 的 ctor 的字符串对象的生命周期是多少?
【发布时间】:2016-12-12 01:44:28
【问题描述】:

根据cppreferencesexplicit runtime_error( const std::string& what_arg );不会复制what_arg的内容。

我可以安全地将临时字符串对象传递到std::runtime_errorctor 吗?

例如:

std::string GetATempString(const char* msg)
{
    return { msg };
}

int main()
{
    try {
        throw std::runtime_error(GetATempString("Hello"));
    } catch (const std::runtime_error& e) 
    {
            e.what(); // Is it guaranteed that "Hello" would be returned safely?
    }
}

【问题讨论】:

  • 哪里说内容没有被复制?

标签: c++ c++11 exception standards object-lifetime


【解决方案1】:

你误会了。 std::runtime_error 总是将字符串复制到一个引用计数的写时复制内部缓冲区,因为它可能不会在以后复制时抛出异常。

【讨论】:

  • "reference-counted copy-on-write" - 为什么?什么时候修改字符串?
猜你喜欢
  • 2021-09-25
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-27
相关资源
最近更新 更多