gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:44:21 28 4
gpt4 key购买 nike

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

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com