Temporary std::strings returning junk

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

提交回复
热议问题