Closed mantaraya36 closed 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
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?
No, it will be initialized only once since it is static. It does exactly what we want. Try the following:
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(); }
Absolutely right. I must have done my initial tests wrong, as I am now getting the right result with multiple calls to Domain::master().
Whenever master() is called, a new instance is allocated rather than reused:
https://github.com/LancePutnam/Gamma/blob/devel/src/Domain.cpp#L114