c++ - std::string::substr 返回的对象的生命周期

标签 c++ string c++11 lifetime temporary

我需要知道以下内容总体上是否有效。

string s = "some value";
string v = s.substr(0, 50).c_str();

v的赋值总是有效吗?由于 substr() 返回的对象的临时生命周期会导致任何问题吗?

最佳答案

这里有效。 temporary substr 返回的内容在完整表达式之后被销毁;其中包括 v 的初始化。

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that evaluation ends in throwing an exception.

顺便说一句:这不是赋值,而是 v 的初始化(构造)。

关于c++ - std::string::substr 返回的对象的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58239144/

相关文章:

javascript - 在 JavaScript 中解析一个整数(并且*仅*一个整数)

php - 如何在一个部分是数字而另一部分是“int”的单词之间替换...?

c++ - 声明在嵌套范围内初始化的未初始化变量

c++ - 如何使用 QEventLoop 同步等待多个 QNetwork 回复?

c++ - 通过 sscanf 读取全名

Python 浮点字符串格式不正确

c++ - 可变参数模板之谜

linux - 代码中 Linux 时间和性能时钟之间的区别

C++ ifstream 和 ofstream 重载运算符从文件读取

c++ - 如何在父类型中限制子类型?