Temporary std::strings returning junk

后端 未结 3 396
独厮守ぢ
独厮守ぢ 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();
    } 
    

提交回复
热议问题