Why is my fstream being implicitly deleted?

Andy E picture Andy E · Sep 15, 2012 · Viewed 23.1k times · Source

I'm working with a few HID devices, all of which have classes deriving from the following base class (in main.h):

class HIDDevice {
    public:
        hid_device *device;

        virtual void read(std::fstream)=0;
        virtual void write(std::fstream)=0;
};

Here's one of the device classes deriving from it (device.h):

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

...and a sample of the implementation:

void MyDevice::read(std::fstream file) {
    // Read from card and write to file
    response = send_command(READ_DEVICE);
    file.write((char *)&response[0], response.size());
}

...and the caller:

fstream file (filename, ios::binary | ios::in);
dev->read(file);

When I try and compile, I get the following error:

main.cpp:294:27: error: use of deleted function ‘std::basic_fstream::basic_fstream(const std::basic_fstream&)’
In file included from source/main.cpp:24:0: /usr/include/c++/4.6/fstream:761:11: error: ‘std::basic_fstream::basic_fstream(const std::basic_fstream&)’ is implicitly deleted because the default definition would be ill-formed:

... and I have no idea why, probably because I'm fairly new to C++ and I've done something idiotic.

Changing the arguments back to references (using &), I get the following error:

/main.o:(.rodata._ZTV13MyDevice[vtable for MyDevice]+0x18): undefined reference to `MyDevice::write(std::basic_fstream >&)'

Can anyone help me fix this problem?

Answer

WhozCraig picture WhozCraig · Sep 15, 2012

Try tossing those std::fstreams around by reference.

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