Originally, I have some code that looks like
class Ball
{
public:
double x , y ;
ofstream out ;
} ;
int main()
{
Ball array[N] ;
array[0].out.open("./position_1.txt") ;
array[1].out.open("./position_2.txt") ;
......
}
where N is a run-time determined constant.
But it suffers variable length arrays problem recently.
I try to follow the suggestion by this post Can't set variable length with variable by using STL container.
int main()
{
vector<Ball> Balls ;
Ball b ;
b.out.open( "./position_1.txt" ) ;
Balls.push_back( b ) ;
......
}
It fails at push_bak(), since stream can not be copied.
I can’t determine the number of balls before running and I have to store the file stream instead of path for efficiency (preventing opening and closing files).
Is there any way to achieve the goal?
Thanks
C++ streams are not copyable, but they’re movable, so you can do this instead:
and the default move-semantic generated by compiler for your class will work fine with this.
In C++11, you can write this:
Note that this will not work in C++03, as in C++03 vector’s constructor creates N copies of a default created object of type
Ball. In C++11, however, it doesn’t make any copy!