我正在创建一个包含以下部分的记录器:
// #define LOG(x) // for release mode
#define LOG(x) log(x)
log(const string& str);
log(const ostream& str);
Run Code Online (Sandbox Code Playgroud)
有了这样的想法:
LOG("Test");
LOG(string("Testing") + " 123");
stringstream s;
LOG(s << "Testing" << 1 << "two" << 3);
Run Code Online (Sandbox Code Playgroud)
这一切都按预期工作,但当我这样做时:
LOG(stringstream() << "Testing" << 1 << "two" << 3);
Run Code Online (Sandbox Code Playgroud)
这是行不通的:
void log(const ostream& os)
{
std::streambuf* buf = os.rdbuf();
if( buf && typeid(*buf) == typeid(std::stringbuf) )
{
const std::string& format = dynamic_cast<std::stringbuf&>(*buf).str();
cout << format << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
导致'format'包含垃圾数据而不是通常正确的字符串.
我认为这是因为<<运算符返回的临时ostream比它来自的字符串流更长.
还是我错了?
(为什么string()以这种方式工作?是因为它返回对它自己的引用吗?我假设是的.)
我真的很想这样做,因为我在登录发布模式时会省去额外的分配.
任何以这种方式完成任务的指针或技巧都会受到欢迎.在我的实际解决方案中,我有许多不同的日志功能,它们都比这更复杂.所以我更希望在调用代码中以某种方式实现它.(如果可能的话,不要修改我的#define) …