G++ and constructors

Sean MacLennan seanm@seanm.ca
Tue Mar 6 02:37:00 GMT 2007


Hi,

I have been warned that the following can happen under another compiler. 
I don't think it can happen with g++, and frankly I don't think it can 
happen, but I was wondering if anybody could give a definitive answer.


We have a singleton and a method to get the singleton that creates it if 
necessary. Assume lock and unlock just work ;)

static myclass *instance = NULL;

static myclass *myclass::get_instance()
{
	if(instance == NULL) {
		lock();
		if(instance == NULL)
			instance = new myclass();
		unlock();
	}

	return instance;
}

What was argued was that the new can be split it two parts. It can 
allocate the memory, assign this memory to instance, *then* call the 
constructor. So you have a race condition in a multi-threaded system 
where instance is non-null, but has not yet been initialized.

I always thought that the new would not return until *after* the 
constructor had been called. Therefore, no race condition.

I don't need work-arounds, I just need to know if the code ever could be 
split.

Cheers,
    Sean MacLennan



More information about the Gcc-help mailing list