From what I understand, the C++ template class reference_wrapper
is useful for references in containers and tuples, because it essentially provides a copy-constructor and assignment operator to normal references. In other words, it seems to be like a pointer that does not allow null.
Based on that understanding, I tried to implement a class that prints strings to std::cout
by default but allows the user to override that with a file. This is probably not useful for any real-world program; I just use it here as an example. As an exercise in modern C++, I wanted to avoid using new/delete and rely on RAII features. Here's what the class looks like:
class Printer {
public:
Printer() : myOut(std::cout)
{}
void print(string str)
{
myOut.get() << str << endl;
}
void setFileOutput(string path)
{
fileOutput.reset(new ofstream(path));
myOut = *fileOutput;
}
private:
reference_wrapper<ostream> myOut;
unique_ptr<ofstream> fileOutput;
};
Everything works as expected, but this is quite a different use case from examples of reference_wrapper
I've found online. Is this considered to be a valid use of reference_wrapper
? Is there a better alternative that uses modern C++ features such as automatic resource management and RAII?