Reputation:
In main I have started an ofstream
like this:
std::ofstream to(argv[2]);
Now I want to move it (not a copy) to my class builder like this:
class MyClass{
std::ofstream output;
MyClass(const std::ofstream &output=std::cout) output(output): {}
};
But that pops up many errors, any idea why is this happening?
Upvotes: 0
Views: 38
Reputation: 597941
Your code fails because you are trying to take a copy of the ofstream
, but C++ streams are not copyable.
If you are using C++11 or later, you can use actual move semantics, eg
class MyClass{
std::ofstream output;
public:
MyClass(std::ofstream &&output) : output(std::move(output)) {}
};
...
std::ofstream to(argv[2]);
MyClass cls(std::move(to));
Otherwise, use a non-owning reference or pointer instead (just make sure the stream outlives your class):
class MyClass{
std::ofstream &output;
public:
MyClass(std::ofstream &output) : output(output) {}
};
...
std::ofstream to(argv[2]);
MyClass cls(to);
class MyClass{
std::ofstream *output;
public:
MyClass(std::ofstream *output) : output(output) {}
};
...
std::ofstream to(argv[2]);
MyClass cls(&to);
Or, you could simply change your constructor to take a filename instead of a pre-existing stream:
class MyClass{
std::ofstream output;
public:
MyClass(const char *filename) : output(filename) {}
};
...
MyClass cls(argv[2]);
Upvotes: 1
Reputation: 60278
Instead of moving the ostream
you should take a reference to it. Also, your class should contain a ostream&
otherwise a default constructed MyClass
will not work. Also, the constructor should take an ostream&
, instead of const ofstream&
, like this:
class MyClass{
std::ostream &output;
public:
MyClass(std::ostream &output = std::cout) : output(output) {}
};
Here's a demo.
Upvotes: 2