LancePutnam / Gamma

Generic (Sound) Synthesis Library
Other
458 stars 54 forks source link

Singleton master domain not enforced #28

Closed mantaraya36 closed 9 years ago

mantaraya36 commented 9 years ago

Whenever master() is called, a new instance is allocated rather than reused:

https://github.com/LancePutnam/Gamma/blob/devel/src/Domain.cpp#L114

LancePutnam commented 9 years ago

Actually, it is not re-allocated, but initialized on first use since it is static. This is an intended pattern to avoid the "static initialization fiasco". See:

http://www.parashift.com/c++-faq/static-init-order-on-first-use.html http://www.parashift.com/c++-faq/construct-on-first-use-v2.html

mantaraya36 commented 9 years ago

Yes, but the issue is that if you call the master() function multiple times, it will allocate a new master each time. You need to set some sort of static marker to know whether the master domain has been already allocated. Or maybe I am reading the idea wrong and you would want to create new masters every time you call that function?

LancePutnam commented 9 years ago

No, it will be initialized only once since it is static. It does exactly what we want. Try the following:

include <stdio.h>

struct A{ A(){ printf("created A @ %p\n", this); } };

struct B{ static A& master(){ static A * result = new A; printf("getting A @ %p\n", result); return *result; } };

int main(){ B::master(); B::master(); }

mantaraya36 commented 9 years ago

Absolutely right. I must have done my initial tests wrong, as I am now getting the right result with multiple calls to Domain::master().