samedi 2 mai 2020

Move constructor not inherited nor default generated

I tried extending std::ifstream with one function to make it easier to read binary variables, and to my surprise, with using std::ifstream::ifstream; the move constructor is not inherited. Worse yet, it is explicitly deleted.

#include <fstream>

class BinFile: public std::ifstream
{
public:
    using std::ifstream::ifstream;
    //BinFile(BinFile&&) = default; // <- compilation warning: Explicitly defaulted move constructor is implicitly deleted

    template<typename T>
    bool read_binary(T* var, std::streamsize nmemb = 1)
    {
        const std::streamsize count = nmemb * sizeof *var;
        read(reinterpret_cast<char*>(var), count);
        return gcount() == count;
    }
};

auto f()
{
    return std::ifstream{}; // Works!
    // return BinFile{}; // <- compilation error: Call to implicitly-deleted copy constructor of 'BinFile'
}

I don't want to explicitly implement the move constructor because it just feels wrong. Questions:

  1. Why it is deleted?
  2. Does it makes sense for it to be deleted?
  3. Is there a way to fix my class so that the move constructor is properly inherited?

Aucun commentaire:

Enregistrer un commentaire