Why do I make “use of deleted” function when passing a std::ofstream as parameter? [duplicate]

余生颓废 提交于 2021-02-04 17:48:02

问题


I have a member that is std::ofstream fBinaryFile and a

void setFile( std::ofstream& pBinaryFile ) 
{
    fBinaryFile = pBinaryFile;
}

output:

 Data.h:86:16: error: use of deleted function ‘std::basic_ofstream<char>& std::basic_ofstream<char>::operator=(const
 std::basic_ofstream<char>&)’
     fBinaryFile = pBinaryFile;
                 ^

I understood that copy in std::ofstream is not allowed and maybe I'm missing something. Is possible save the content of pBinaryFile in fBinaryfile?


回答1:


Because the relevant operator is declared as

ofstream& operator= (const ofstream&) = delete;

which means it is explicitly prohibited so ofstream semantics does to support copying.

Depending on your architecture you can store a pointer/reference or move it.




回答2:


If you want to copy the content of pBinaryFile to fBinaryFile you need to declare pBinaryfile as an ifstream (input file stream), not an ofstream (output file stream) It should look something like this:

std::ifstream pBinaryFile;
std::ofstream fBinaryFile;
std::stringstream sstream;
std::string line
pBinaryFile.open(pBinaryFileName.c_str());
fBinaryFile.open(fBinaryFileName.c_str());
if (pBinaryFile.isopen()) {
    while (pBinaryFile.good()) {
        getline(pBinaryFile, line);
        fBinaryFile << sstream(line) << endl;
    }
}
pBinaryFile.close();
fBinaryFile.close();

Note that pBinaryFileName and fBinaryFileName refer to the paths of your files.

There might be mistakes in this code, but I think the solution looks similar to this.

I suggest this for further reading:

http://www.cplusplus.com/doc/tutorial/files/



来源:https://stackoverflow.com/questions/31674353/why-do-i-make-use-of-deleted-function-when-passing-a-stdofstream-as-paramete

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