c – 临时std :: strings返回垃圾
发布时间:2020-12-16 03:39:10 所属栏目:百科 来源:网络整理
导读:我还在学习c,所以请耐心等待.我正在编写一个关于boost文件系统路径的简单包装器 – 我在返回临时字符串方面遇到了奇怪的问题.这是我的简单类(这不是确切的,但非常接近): typedef const char* CString;typedef std::string String;typedef boost::filesystem
我还在学习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 ?t?t?t?t?t?t?t?t?t?t?.....) 我很确定这必须处理临时工,但我无法弄清楚为什么会这样 – 不应该一切都正确复制? 解决方法
看起来像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(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |