微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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();
}

原文地址:https://www.jb51.cc/c/110815.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐