这是定义的行为吗?

问题描述 投票:0回答:1
    #include <string>
    #include <iostream>
    
    void Print(const char* s) {
        std::cout << s << std::endl;
    }
    
    std::string GetString() {
        std::string ret;
        ret = "Is this defined behavior?";
        return ret;
    }
    
    int main() {
        Print(GetString().c_str());
    }

这段代码似乎可以在三大编译器上可靠地工作。我担心它实际上可能不是定义的行为,是否可能会破坏字符串,使 c_str() 返回的指针在调用 Print 函数之前悬空?

https://godbolt.org/z/cKddvd1aP

c++ undefined-behavior
1个回答
0
投票

这是完全明确定义的行为。

GetString()
返回一个临时的
std::string
,当创建它的完整表达式结束时,它将被销毁。这意味着在
;
退出后,它会在
Print()
上被销毁,因此
c_str()
指针不会在
Print()
内部悬空。

© www.soinside.com 2019 - 2024. All rights reserved.