临时std ::字符串返回垃圾 [英] Temporary std::strings returning junk
问题描述
我还在学习c ++,所以请和我一起玩。我正在写一个简单的包装程序boost文件系统路径 - 我有返回临时字符串的奇怪问题。这是我的简单类(这不是精确,但很接近):
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. Here's my simple class (this is not exact, but pretty close):
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;
}
使用下面的小测试代码:
With the little test code below:
FileReference file("c:\\test.txt");
OutputDebugString(file.path().c_str()); // returns correctly c:\test.txt
OutputDebugString(file.c_str()); // returns junk (ie îþîþîþîþîþîþîþîþîþîþî.....)
处理临时,但我不知道为什么会是 - 一切都应该正确复制?
I'm pretty sure this has to deal with temporaries, but I can't figure out why that would be -- shouldn't everything be copying correctly?
推荐答案
看起来像 mPath.string()
按值返回一个字符串。一旦FileReference :: c_str()返回,临时字符串对象就被销毁,所以它的c_str()变得无效。使用这样的模型,不能创建 c_str()
函数,而不为字符串引入某种类或静态级变量。
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.
考虑以下替代方法:
//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();
}
这篇关于临时std ::字符串返回垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!