Why is my fstream being implicitly deleted?

大兔子大兔子 提交于 2019-12-05 01:29:16

Try tossing those std::fstreams around by reference.

class MyDevice : public HIDDevice {
    public:
        void read(std::fstream&);
        void write(std::fstream&);
};

Just for reference, I had the same compiler error, but created it in a different way that wasn't immediately obvious to me. Out of habit I wrote:

auto stream = fstream(output, iOS::out | iOS::binary);

Which, of course, creates a temporary fstream object and copies it to stream. That worked in Xcode 6 using clang, but not for GCC 4.9.2.

The HIDDevice method signatures mean that the fstreams are being passed around by value. This in turn means that copies of the original stream objects have to be created at the call site using the copy constructor. It is this copy constructor that has the canonical signature std::basic_fstream::basic_fstream(const std::basic_fstream&).

The compiler is telling you that for some reason (which has to do with the particulars of the basic_fstream implementation your standard library uses) it cannot auto-generate this copy constructor, hence it cannot fulfill your implicit command to make copies of the streams.

As others have already said, the usual modus operandi (which will also prevent the error here) is to pass the arguments by reference instead of by value.

&std::fstream as a parameter will pass it around by reference to be used as the same object everywhere. This avoids the implementation trying to create another instance and then closing the stream when the functions end (because the copied object is being destructed).

Make sure you change this in both the declaration and the implementation of the member function (i.e. in the class and where the body is).

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