Temporary std::strings returning junk

后端 未结 3 437
独厮守ぢ
独厮守ぢ 2021-01-18 13:14

I\'m still learning c++, so please bear with me. I\'m writing a simple wrapper around boost filesystem paths -- I\'m having strange issues with returning temporary strings.

3条回答
  •  忘掉有多难
    2021-01-18 13:47

    Expressions

    OutputDebugString(file.path().c_str())
    

    and

    OutputDebugString(file.c_str())
    

    are similar in that they both effectively call c_str() method on a temporary std::string object and attempt to use the result of that call. The first one calls it directly as file.path().c_str() subexpression. The second one does it more implicitly: inside FileReference::c_str() method.

    In the first case the temporary std::string object is explicitly created by file.path() call as an immediate part of the entire expression. In accordance with the rules of the language the lifetime of that temporary object extends to the end of the whole expression, which is why the temporary and the result of c_str() call remain valid throughout.

    In the second case the temporary std::string object is created inside FileReference::c_str() method. That temporary object is destroyed when this method returns, meaning that FileReference::c_str() returns a pointer to "dead" data. This is the reason for the "junk" in question.

提交回复
热议问题