Search code examples
c++fstreamdeleted-functions

C++: Deleted function when trying to pass fstream as argument?


I don't know what is wrong with my code. I am trying to get a file path from the console for two files, then I initialize some fstream objects with those files and ios::in | ios::out for one, and an addition of ios::binary for the other.

Here are the important parts of my code:

// Function prototypes
void INPUT_DATA(fstream);
void INPUT_TARGETS(fstream);

int main()
{
    // Ask the user to specify file paths
    string dataFilePath;
    string targetsFilePath;
    cout << "Please enter the file paths for the storage files:" << endl
        << "Data File: "; 
    getline(cin, dataFilePath); // Uses getline() to allow file paths with spaces
    cout << "Targets File: "; 
    getline(cin, targetsFilePath);

    // Open the data file
    fstream dataFile;
    dataFile.open(dataFilePath, ios::in | ios::out | ios::binary);

    // Open the targets file
    fstream targetsFile;
    targetsFile.open(targetsFilePath, ios::in | ios::out);

    // Input division data into a binary file, passing the proper fstream object        
    INPUT_DATA(dataFile);

    // Input search targets into a text file
    INPUT_TARGETS(targetsFile);

    ...
}

// Reads division names, quarters, and corresponding sales data, and writes them to a binary file
void INPUT_DATA(fstream dataFile)
{
    cout << "Enter division name: ";
    ... 
    dataFile << divisionName << endl;
    ...
}

// Reads division names and quarters to search for, and writes them to a file
void INPUT_TARGETS(fstream targetsFile)
{
    cout << "\nPlease input the search targets (or \"exit\"):";
    ...
    targetsFile.write( ... );
    ...
}

However, Visual Studio yells at me on the INPUT_DATA(dataFile); and INPUT_TARGETS(targetsFile); parts, saying:

function "std::basic_fstream<_Elem, _Traits>::basic_fstream(const std::basic_fstream<_Elem, _Traits>::_Myt &) [with _Elem=char, _Traits=std::char_traits<char>]" (declared at line 1244 of "c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\fstream") cannot be referenced -- it is a deleted function

I dug around in the header file until I found line 1244:

basic_fstream(const _Myt&) = delete;

I have no idea why this is happening. I'm still fairly new to C++ and I've probably just done something idiotic, but could someone please help?

EDIT: Clarified title


Solution

  • You can't copy a std::fstream, so the copy constructor is deleted, as you found out by digging around :)

    There is also no reason to copy a std::fstream. In your case, you want to pass it by reference, because you want to modify the original std::fstream, the one you created in main, and not create a whole new one (that's why the copy constructor is deleted, btw :)).