【发布时间】:2012-03-26 15:20:25
【问题描述】:
可能重复:
Printing a string to a temporary stream object in C++
std::ostringstream printing the address of the c-string instead of its content
我正在尝试使用 stringstream 构建一个字符串,就像您使用 cout 一样。这类似于日志记录类。我遇到的问题是,如果
// class I use to print out the stream
class StreamWriter
{
public:
StreamWriter()
{}
~StreamWriter()
{
std::string myMessage = m_stringstream.str();
std::cout << myMessage << std::endl;
}
std::stringstream m_stringstream;
};
// macro for simplification
#define OSRDEBUG (StreamWriter().m_stringstream)
// actual use
OSRDEBUG << "Hello " << "my " << "name is Pris " << 123456;
// output
0x8054480my name is Pris 123456
0x8054480my name is Pris 123456
0x8054480my name is Pris 123456
0x8054480my name is Pris 123456
任何人都可以阐明发生了什么,以及我该如何解决这个问题?
编辑: 以下更改(除了 padiablo 的示例)同样有效,保持类的析构函数与宏的使用。
// class I use to print out the stream
class StreamWriter
{
public:
StreamWriter()
{ m_stringstream = new std::stringstream; }
~StreamWriter()
{
std::string myMessage = m_stringstream.str();
std::cout << myMessage << std::endl;
delete m_stringstream;
}
std::stringstream * m_stringstream;
};
// macro for simplication
#define OSRDEBUG *(StreamWriter().m_stringstream)
但最初的问题仍然存在,因为它看起来应该可以工作......而且我认为知道何时将其放入生产质量代码可能很重要。
【问题讨论】:
-
有什么理由不使用
#define OSRDEBUG std::cout? -
@Xeo:啊,不错的收获,就在几周前,我也问了我的问题。不过,自从 Nawaz 很好地解释了根本原因并给出了解决方法后,我已经将其“重定向”到了我的。
标签: c++ pointers stringstream memory-address