Global vs local streams in a multithreaded app

D

daniel.bron

I'm maintaining a C++ application written by a developer who has now
left. The app is a multithreaded client/server app for financial data.
My compiler is MS visual C++ 6.0.

I'm a C++ neophyte. I took some C (not C++) courses in college, this is
the only production C++ code I've worked with.

I'm trying to add some logging, and having problems.

My logging scheme is to have a global ofstream, which I initialize in a
function by creating a local ofstream, preparing it, and assigning it
to the global name.

The problem is that I can << to the local name without trouble, but I
get an access violation when I try to << to the global stream (after
assigning global = local).

I think the problem may be due to the multithreaded nature of the
application, but am unsure. At the moment, I'm only <<ing to the log
in one function, in the main (server) thread of the app. There are no
multiple concurrent accesses to the global log.

This code demonstrates the nub of the problem:

-----Globals.h-------

#include <fstream>

class GLOBALS
{
public:
ofstream GlobalLog;
}



------SomeOtherFile.cpp-------
#include "Globals.h"

extern GLOBALS * g; // This is populated properly, I just don't show
that here.

void foo()
{
if(!g->GlobalLog.is_open())
{
ofstream localNameForTheLog("c:\\thelogIwant.log" , ios::eek:ut |
ios::ate | ios::app);

if(!localNameForTheLog.is_open())
{
cout << "Couldn't open log.";
return;
}

localNameForTheLog << "Some stuff I'm able to log successfully";

g->GlobalLog = localNameForTheLog;

}

// If we got here, either GlobalLog was already open,
// or we just successfully opened it.
g->GlobalLog << "This causes an access violation for some reason, even
though I just logged the line above.";

}
 
P

Pete Becker

g->GlobalLog = localNameForTheLog;

iostreams aren't assignable. This line only "works" because there is a
secret assignment operator that's used during initialization. It doesn't
do a proper assignment, though.

But there's no need to go through all this indirection. Just open the
global stream using ofstream::eek:pen.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top