I'm using a third-party class with (only) constructor as follows
class foo // cannot be altered
{
public:
explicit foo(std::istream&);
...
};
and the documentation of which suggests the following approach
std::ifstream from("file.txt");
foo obj(from);
from.close();
I cannot alter foo
and want to use as member of another class
class bar
{
foo obj; // must not be altered
public:
explicit
bar(std::string const&filename) // must not be altered
: obj(std::ifstream(filename)) // error: no matching constructor
{}
...
};
except that this does not work, since the temporary std::ifstream
created from the filename
is not guaranteed to live long enough to construct the foo obj
and hence cannot be converted to a std::istream&
(the situation would be different, if foo::foo()
accepted a const std::istream&
).
So my question: can I make the constructor of bar
to work without changing the design of bar
(for example, bar::bar()
to take a std::istream&
, or bar to hold a std::unique_ptr<foo>
instead of a foo
or by adding data members to bar
)?