Question

I would like to write my output to a file if a file name is avaliable or on the screen (stdout) otherwise. So I've read posts on this forum and found a code, which below I wrapped into a method:

std::shared_ptr<std::ostream> out_stream(const std::string & fname) {

std::streambuf * buf;
std::ofstream of;

if (fname.length() > 0) {
    of.open(fname);
    buf = of.rdbuf();
} else
    buf = std::cout.rdbuf();

std::shared_ptr<std::ostream> p(new std::ostream(buf));
return p;
}

The code works perfectly when used in-place. Unfortunately it behaves oddly when wrapped into a separate method (as given above). Is it because the the objects defined within the method (of, buff) are destroyed once the call is finished?

I am using this part of code in several places and it really should be extracted as a separate non-repeating fragment: a method or a class. How can I achieve this?

Was it helpful?

Solution

You're correct that the problems you're having come from the destruction of of. Wouldn't something like this (untested) work?

std::shared_ptr<std::ostream>
out_stream(const std::string &fname) {
    if (fname.length() > 0)
        std::shared_ptr<std::ostream> p(new std::ofstream(fname));
    else
        std::shared_ptr<std::ostream> p(new std::ostream(std::cout.rdbuf()));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top