我还在学习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;
}
Run Code Online (Sandbox Code Playgroud)
使用下面的小测试代码:
FileReference file("c:\\test.txt");
OutputDebugString(file.path().c_str()); // returns correctly c:\test.txt
OutputDebugString(file.c_str()); // returns junk (ie îþîþîþîþîþîþîþîþîþîþî.....)
Run Code Online (Sandbox Code Playgroud)
我很确定这必须处理临时工,但我无法弄清楚为什么会这样 - 不应该一切都正确复制?
所以我在实习的技能测试中被问到这个问题,当时它让我完全感到困惑.我现在有一些代码,我认为应该可以工作,但是没有为字符串分配正确的值.
#include <iostream>
#include <string>
using namespace std;
int main()
{
// declarations
int i = 0, num= 63;
string b="";
while (num != 0)
{
i = num % 10;
b.insert(0,i + 48 + "");
num = num/10;
}
cout << b << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
"num"是整数值(我只用63作为例子)
编辑::我错误地解释,我不能使用任何为我做字符串转换的函数,而不是我不能使用字符串库,我的错误.
从ildjarn读完这个答案之后,我编写了以下示例,它看起来像一个未命名的临时对象与其引用具有相同的生命周期!
源代码:
#include <iostream> //cout
#include <sstream> //ostringstream
int main ()
{
std::ostringstream oss;
oss << 1234;
std::string const& str = oss.str();
char const* ptr = str.c_str();
// Change the stream content
oss << "_more_stuff_";
oss.str(""); //reset
oss << "Beginning";
std::cout << oss.str() <<'\n';
// Fill the call stack
// ... create many local variables, call functions...
// Change again the stream content
oss << "Again";
oss.str(""); //reset
oss << "Next should …Run Code Online (Sandbox Code Playgroud)