Temporary std::strings returning junk

后端 未结 3 395
独厮守ぢ
独厮守ぢ 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:43

    Looks like mPath.string() returns a string by value. That temporary string object is destructed as soon as FileReference::c_str() returns, so its c_str() becomes invalid. With such a model, it's not possible to create a c_str() function without introducing some kind of class- or static-level variable for the string.

    Consider the following alternatives:

    //Returns a string by value (not a pointer!)
    //Don't call it c_str() - that'd be misleading
    String str() const
    {             
         return mPath.string();
    } 
    

    or

    void str(String &s) const
    {             
         s = mPath.string();
    } 
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-18 13:49
    CString c_str() const {
            return mPath.string().c_str();
        };
    

    mPath.string() returns a copy of a std::string. That copy is stored in a temporary which will be destroyed at the end of this expression.

    .c_str() returns a pointer to memory which will be destroyed when the string is destroyed, i.e. at the end of this expression.

    You are returning a pointer to memory which is already destroyed.

    0 讨论(0)
提交回复
热议问题