Why can't an object containing a ostringstream member be constructed?

自作多情 提交于 2019-12-01 08:43:48

This would work fine:

Container cont;
cont.bufferStream << "world!";

But this:

Container cont = Container();

involves the copy constructor. std::ostringstream is not copy-constructible which makes Container not copy-constructible, hence the error message talking about how Container::Container(const Container&) is implicitly deleted due to std::basic_ostringstream<char>::basic_ostringstream(const std::basic_ostringstream<char>&) being implicitly deleted.

Note that even though this copy would be elided, a requirement of copy/move elision is that the copy/move must be possible to begin with.

Christophe

As Barry explained, the ostringstream isn't copy constructible. As the default copy constructor copy-constructs member by member, it can't be generated here.

However, if you'd follow the rule of three you'd create a copy constructor (and also a copy assignment operator), doing what is needed for the stringstream. Then it would work:

class Container {
    ...
    Container(const Container&); //Copy constructor
};  

Container::Container(const Container &c) {
    bufferStream << c.bufferStream.rdbuf(); 
}

Online demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!