c – 临时std :: strings返回垃圾

我还在学习c,所以请耐心等待.我正在编写一个关于boost文件系统路径的简单包装器 – 我在返回临时字符串方面遇到了奇怪的问题.这是我的简单类(这不是确切的,但非常接近):
typedef const char* CString;
typedef std::string String;
typedef boost::filesystem::path Path;

class FileReference {

    public:

        FileReference(const char* path) : mPath(path) {};

        // returns a path
        String  path() const {
            return mPath.string();
        };

        // returns a path a c string
        CString c_str() const {
            return mPath.string().c_str();
        };

    private:

        Path    mPath;

}

使用下面的小测试代码

FileReference file("c:\\test.txt");

OutputDebugString(file.path().c_str()); // returns correctly c:\test.txt
OutputDebugString(file.c_str());        // returns junk (ie îþîþîþîþîþîþîþîþîþîþî.....)

我很确定这必须处理临时工,但我无法弄清楚为什么会这样 – 不应该一切都正确复制?

解决方法

看起来像mPath.string()按值返回一个字符串.一旦FileReference :: c_str()返回,该临时字符串对象就被破坏,因此其c_str()变为无效.使用这样的模型,如果不为字符串引入某种类或静态级变量,则无法创建c_str()函数.

考虑以下备选方案:

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

要么

void str(String &s) const
{             
     s = mPath.string();
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...