Kristian Nielsen <knielsen@knielsen-hq.org> writes:
Or compilers could optimise based on knowledge that no external code can modify a private member (so it does not need to be spilled over a call to pthread_mutex_lock() or similar). But none of this would give a problem with bzero-initialisation after alloc.
Hm, thinking more - I am not sure I was correct with this statement. Consider the following code: class GenId { private: int current; public: int next() { return current++; } } GenId *p= malloc(sizeof(GenId)); memset(p, 0, sizeof(GenId)); p->next(); What is to prevent the compiler from moving the code around, so that the access to GenId::current inside p->next() happens before the memset()? After all, GenId::current is private, there is no code outside of class GenId that is allowed to change it. So this would seem a "correct" optimisation, and the code will run with an uninitialised value for current. This is precisely the kind of problem we want desparately to avoid: A new compiler on a new platform comes out, and it does this optimisation, and some poor seniour developer has to spend days to find a way to reproduce and figure out why some strange case crashes. So I can only agree more with Davi here: let's avoid this. Make all members public. Or use placement new instead of bzero() to initialise. - Kristian.