Re: utilizing a map with ofstreams, and a map with mutexes
ictheion wrote:
I have a map of <char, ofstream*> & a map of <char,
mutex*>. I can compile this program, I am getting errors at
runtime. I am able to set up the maps, but I am unable to access the
ofstreams or mutexes I need.
I have stored these in a map because I require access to 26
files, but I cannot open and close them each time I need access,
because of efficiency, I also realize that this could be done more
easily from an array, but i'm concerned with how to use the map
container specifically.
Ok.
Here is some of the relevant code, This is a multi-threaded program
and I also have a map<char, boost::mutex*>, which I am having
the same issues with. Any advice?
[..]
typedef map<char, ofstream*> map_type;
typedef map<char, mutex*> mutex_type;
[..]
map_type::iterator i = stream_map.find(first);
mutex_type::iterator j = mutex_map.find(first);
mutex::scoped_lock lock (( *j->second ) );
//won't work
(*i->second) << w << endl;
//won't work
This code compiles and it is not faulty per se, but there are things to
improve:
1. Make sure the pointer is valid. Use assert() to make sure that the
pointers are not null. Use a smart pointer (tr1::shared_ptr or
boost::shared_ptr) come to mind to avoid even having a dangling pointer.
2. If you always access both the stream and the mutex together, you
could
bundle them in a structure. This would half the overhead of the maps
since
you only need one of them.
Now, what I'm concerned about is how you insert the streams into the
map.
You don't create them as automatic variables (i.e. on the stack) but
with 'new', rigth?
Also, what do you mean when you say "won't work"? This is essential for
error diagnosis.
Uli
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]