我需要知道以下内容总体上是否有效。
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/