Search code examples
c++functionifstreamdeleted-functions

std::ifstream, use of deleted function


I am trying to write a method which will get data from a .txt file.

I need to call this method from other methods. I have a problem with passing arguments to methods.

Library.h:

#include <iostream>
#include <vector>
#include <string>
#include <fstream>

class Library
{
   std::vector<std::string> &mBooks;
   std::string books_list;
   std::string output;
   std::string books_path;

   void read_file(std::string &fn, std::ifstream &fn_var, std::string 
        &s, std::vector<std::string> &vn);
   void create_books_database(std::string &fn, std::ifstream,&fn_var,
        std::string &s, std::vector<std::string> &vn);
};

Library.cpp:

void Library::read_file(std::string &fn, std::ifstream &fn_var, 
std::string &s, std::vector<std::string> &vn)
{ 
    std::string &filename = fn;
    std::ifstream &name = fn_var;
    std::string &output = s;
    std::vector<std::string> &vector_name = vn;

    name.open(filename);

    if(!name)
    {
        std::cerr<<"Failed to open file "<<filename<<std::endl;
        exit(1);
    }

    while(!name.eof())
    {
        std::getline(name, output);
        vector_name.push_back(output);
    }
}

void Library::create_books_database(std::string &fn, std::ifstream 
  &fn_var, std::string &s, std::vector<std::string> &vn)
{
    std::string books_path = fn;
    std::ifstream books_list = fn_var;
    std::string output = s;
    std::vector<std::string> mBooks = vn;

    read_file(books_path, books_list, output, mBooks);
}

Error:

src/Library.cpp: In member function ‘void                     
Library::create_books_database(std::__cxx11::string&, std::ifstream&, 
std::__cxx11::string&, std::vector<std::__cxx11::basic_string<char> 
>&)’:
src/Library.cpp:35:32: error: use of deleted function 
‘std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const 
std::basic_ifstream<_CharT, _Traits>&) [with _CharT = char; _Traits = 
std::char_traits<char>]’
 std::ifstream books_list = fn_var;

I think I messed a bit with references.


Solution

  • The books_list variable in create_books_database() is not declared as a reference. You are initializing one std::ifstream object with another, but std::ifstream has a deleted copy constructor so it can't be copied. That is what the error message is saying.

    Change this:

    std::ifstream books_list = fn_var;
    

    To this:

    std::ifstream &books_list = fn_var;
    

    Or, simply get rid of the redundant local variables to begin with. There is no need to declare local reference variables to input parameters, all you are doing to creating extra aliases that don't really benefit anything. The parameters of read_file() are the same as the parameters of create_books_database() so just pass them as-is:

    void Library::create_books_database(std::string &fn, std::ifstream &fn_var, std::string &s, std::vector<std::string> &vn)
    {
        read_file(fn, fn_var, s, vn);
    }