gpt4 book ai didi

C++ 匿名字符串销毁时间

转载 作者:行者123 更新时间:2023-12-01 14:47:09 26 4
gpt4 key购买 nike

我们有一个函数 GetString()返回 std::string .然后我们有一个函数 ConsumeString(char*)使用 C 风格的字符串。
是不是写错了ConsumeString(GetString().c_str()) ?对我来说,这似乎是一个错误,因为在 c_str() 之后运行,原始匿名字符串将被破坏,您将拥有一个指向不再存在的内容的指针。但奇怪的是,它似乎总是工作正常。
当我尝试分配 GetString().c_str() 时,我才注意到这可能是一个问题。到一个变量,然后在两个单独的 ConsumeString() 中使用它函数,此时它打印了一个损坏的字符串,问题变得明显。但我不知道为什么它在前一种情况下似乎有效。
它可能是一个碰巧起作用的错误,还是 C++ 专门允许这样做?

最佳答案

除非 ConsumeString 对 const char* 做了一些异步处理提供给它(直接或间接)这个代码是非常安全的。
GetString() 退回的临时件将一直存活到函数 ConsumeString返回,所以如果它在返回之前完成了它的所有业务,那么一切都会正常工作。
在您的其他情况下 - 我假设,您有这样的事情:

 const char* s = GetString().c_str(); // 1
ConsumeString(s); // 2
临时退回 GetString在第 1 行结束后被销毁,所以 ConsumeString消耗了一个无效的指针。
有关临时对象生命周期的更正式的措辞,可以引用 cppreference , 特别是

All temporary objects are destroyed as the last step in evaluating thefull-expression that (lexically) contains the point where they werecreated, and if multiple temporary objects were created, they aredestroyed in the order opposite to the order of creation.

关于C++ 匿名字符串销毁时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63270037/

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