“ofstream” as function argument

2020-02-02 15:40发布

问题:

Is there a way to pass output stream as argument like

void foo (std::ofstream dumFile) {}

I tried that but it gave

error : class "std::basic_ofstream<char, std::char_traits<char>>" has no suitable copy constructor

回答1:

Of course there is. Just use reference. Like that:

void foo (std::ofstream& dumFile) {}

Otherwise the copy constructor will be invoked, but there is no such defined for the class ofstream.



回答2:

You have to pass a reference to the ostream object as it has no copy constructor:

void foo (std::ostream& dumFile) {}


回答3:

If you are using a C++11 conformant compiler and standard library, it should be ok to use

void foo(std::ofstream dumFile) {}

as long as it is called with an rvalue. (Such calls will look like foo(std::ofstream("dummy.txt")), or foo(std::move(someFileStream))).

Otherwise, change the parameter to be passed by reference, and avoid the need to copy/move the argument:

void foo(std::ofstream& dumFile) {}