Problem with STL

Hello everbody! I just have a problem with the vector class. In the following code line 16 causes the compiler error:

c:\mingw\bin\..\lib\gcc\mingw32\4.5.2\include\c++\bits\ios_base.h|788|error: 'std::ios_base& std::ios_base::operator=(const std::ios_base&)' is private|

Does anyone have a clue about it?? Thanks a lot in advanced!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <fstream>
#include <map>
using namespace std;

class my_class
{
    private:
        ofstream f;
};

int main()
{
    map<int, my_class> my_class_map;
    my_class my_object;

    my_class_map[0]=my_object;
    return 0;
}
It looks like you can't assign instances of std::ios_base (from which ofstream derives). However, line 16 attempts to assign an instance of type my_class and hence assign one ofstream to another, which is not allowed.

Perhaps change your map so that the values are of type my_class* or my_class& rather than my_class. (Have you studied pointers and references yet?)

Note however that by doing this you must ensure that the variables which the values of the map point to must stay alive as long as you use the map, which might require dynamic allocation.

Sorry if this post has become somewhat complicated - I'm not sure what level you're at.
Thanks for your fast response Xander314. I had considered so, and even make the f ofstream in class my_class a pointer, which solves the problem too. But I just want to know why I cann't use a normal (not a pointer nor a reference) object.
You have to be careful making the ofstream a pointer. How were you going to allocate the memory for it, and where were you going to free it? I had some problems a while back from going about this the wrong way...

As for why you can't do it without a pointer, it's because std::ofstream is written in such a way as to disallow it. I'm not quite sure why this is, but presumably copying an ofstream is a bad idea. Then you would have two streams trying to write to the same file, which doesn't work as far as I am aware. (Try saving a text file while having it open in another program.)
Yes, you're right, thanks. The problem is not with the map class, it's just that I cann't assign a fstream obj to another.

Thanks a lot!
ostream objects (ofstream is derived from ostream) are noncopyable. Think about it... an ofstream object is an object used to write to a file. What sense could be made of two independent ofstream objects both trying to write to the same file? That's why they are noncopyable.
Topic archived. No new replies allowed.