C++ C++;内联匿名实例和命名实例之间的差异
在日志上下文中,我希望使用实用程序类的临时实例来收集一些输出,并使用析构函数来处理收集的输出。例如,打印到标准输出,如下所示 我注意到,与命名的自动实例相比,实用程序实例是否构造为内联匿名实例取决于行为差异 命名实例会产生预期的行为和输出。内联实例在执行第一次插入操作时遇到困难,显然只处理简单转换为int的操作数 以这些不同方式使用的实例之间有什么区别C++ C++;内联匿名实例和命名实例之间的差异,c++,C++,在日志上下文中,我希望使用实用程序类的临时实例来收集一些输出,并使用析构函数来处理收集的输出。例如,打印到标准输出,如下所示 我注意到,与命名的自动实例相比,实用程序实例是否构造为内联匿名实例取决于行为差异 命名实例会产生预期的行为和输出。内联实例在执行第一次插入操作时遇到困难,显然只处理简单转换为int的操作数 以这些不同方式使用的实例之间有什么区别 #include <string> #include <sstream> #include <iostream&g
#include <string>
#include <sstream>
#include <iostream>
class Util
{
public:
std::ostringstream m_os;
Util() {}
~Util() { std::cout << m_os.str() << std::endl;}
};
int main (void)
{
// ----------- Using temporary anonymous instance -
// Output does not match expected, and the first insertion seems to
// only be able to handle instances that can be converted to int.
// Following prints "97key=val", but expect "akey=val"
(Util()).m_os << char('a') << std::string("key") << "=" << std::string("val");
// Following prints "0x80491eakey=val", but expect "Plain old C string key=val"
(Util()).m_os << "Plain old C string " << std::string("key") << "=" << std::string("val");
// Following results in syntax error
// error: no match for ‘operator<<’ in ‘Util().Util::m_os <<
(Util()).m_os << std::string("key") << "=" << std::string("val");
// ----------- Using named instance - output matches expected
// Block results in print "akey=val"
{
Util inst;
inst.m_os << char('a') << std::string("key") << "=" << std::string("val");
}
// Block results in print "Plain old C string key=val"
{
Util inst;
inst.m_os << "Plain old C string " << std::string("key") << "=" << std::string("val");
}
// Block results in print "key=val"
{
Util inst;
inst.m_os << std::string("key") << "=" << std::string("val");
}
return 0;
}
#包括
#包括
#包括
类Util
{
公众:
标准:ostringstream m_os;
Util(){}
~Util(){std::cout(Util())
创建一个临时对象。因此,(Util()).m_os
也是一个临时对象
<> >有一些定义<代码>操作程序,它们应该是相同的。你使用什么编译器?还有:$C++——版本C++(SUSELinux)4.4.1[GCC-4S4-BoffRunt 150839修订版]版权(C)2009免费软件基金会公司。最新版本的GCC是4.8。你不能更新你的编译器吗?GCC 4.4.1是4年。@简单的工作原理是你,因为IDENN是编译在C++ 11模式。即使在GCC 4.8,它将(并且应该)失败,如果你不使用C++ 11。
#include <stdio.h>
struct stream
{
stream& operator<<(int)
{ puts("operator<<(int)"); return *this; }
};
stream& operator<<(stream& s, char)
{ puts("operator<<(char)"); return s; }
struct streamwrapper
{
stream s;
};
int main()
{
streamwrapper w;
w.s << 'a'; // outputs operator<<(char)
streamwrapper().s << 'a'; // outputs operator<<(int)
}