G++ and constructors

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux