c – 为什么不能构造包含ostringstream成员的对象?
我有以下类示例,从较大的项目中简化.它基于一个日志框架,它使用记录器的作用域来终止析构函数中的日志条目.
下面的代码不会编译,因为构造函数是一个隐式删除的函数(编辑:不是真),这似乎与std :: ostringstream对象有关.我对此感到困惑,因为我认为我应该能够直接构造一个std :: ostringstream,这意味着我应该能够直接构造一个Container对象. #include <iostream> #include <sstream> class Container { public: std::ostringstream bufferStream; public: Container(); // constructor ~Container(); }; Container::Container() { bufferStream << "Hello "; } Container::~Container() { std::cout << bufferStream.str() << " [end]" << std::endl; } // === Main method === int main() { Container().bufferStream << "world"; // works fine { // causes tons of compiler errors Container cont = Container(); cont.bufferStream << "world!"; } return 0; } 请注意,标记为“正常工作”的行就是这样做的.它似乎实例化了一个匿名的Container对象,它包含一个新的std :: ostringstream,可以直接访问它来输出“world”. Container本身创建消息的“Hello”部分,其析构函数刷新缓冲区. 为什么没有命名和保存Container对象的第二部分正确运行?以下是我得到的错误示例: error.cpp: In function ‘int main()’: error.cpp:28:36: error: use of deleted function ‘Container::Container(const Container&)’ Container cont = Container(); ^ error.cpp:4:7: note: ‘Container::Container(const Container&)’ is implicitly deleted because the default definition would be ill-formed: class Container { ^ error.cpp:4:7: error: use of deleted function ‘std::basic_ostringstream<char>::basic_ostringstream(const std::basic_ostringstream<char>&)’ In file included from error.cpp:2:0: /usr/include/c++/4.8/sstream:387:11: note: ‘std::basic_ostringstream<char>::basic_ostringstream(const std::basic_ostringstream<char>&)’ is implicitly deleted because the default definition would be ill-formed: class basic_ostringstream : public basic_ostream<_CharT,_Traits> … 等等. 解决方法
这样可以正常工作:
Container cont; cont.bufferStream << "world!"; 但是这个: Container cont = Container(); 涉及复制构造函数. std :: ostringstream不是copy-constructible,这使得Container不是可复制构造的,因此错误消息谈论由于std :: basic_ostringstream< char> :: basic_ostringstream(const)而如何隐式删除Container :: Container(const Container&)隐式删除std :: basic_ostringstream< char>&). 请注意,即使此副本将被省略,复制/移动省略的要求是必须可以开始复制/移动. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |