c – 为什么不能构造包含ostringstream成员的对象?

c – 为什么不能构造包含ostringstream成员的对象?,第1张

概述我有以下类示例,从较大的项目中简化.它基于一个日志框架,它使用记录器的作用域来终止析构函数中的日志条目. 下面的代码不会编译,因为构造函数是一个隐式删除的函数(编辑:不是真),这似乎与std :: ostringstream对象有关.我对此感到困惑,因为我认为我应该能够直接构造一个std :: ostringstream,这意味着我应该能够直接构造一个Container对象. #include < 我有以下类示例,从较大的项目中简化.它基于一个日志框架,它使用记录器的作用域来终止析构函数中的日志条目.

下面的代码不会编译,因为构造函数是一个隐式删除的函数(编辑:不是真),这似乎与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>&).

请注意,即使此副本将被省略,复制/移动省略的要求是必须可以开始复制/移动.

总结

以上是内存溢出为你收集整理的c – 为什么不能构造包含ostringstream成员的对象?全部内容,希望文章能够帮你解决c – 为什么不能构造包含ostringstream成员的对象?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1221436.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存