Re: A style question on const char* vs. std::string
Zeljko Vrba wrote:
class transaction_ticket {
private:
static titles_map& titles;
static titles_map& get_titles();
...
};
titles_map& transaction_ticket::titles = get_titles(); [*]
titles_map& transaction_ticket::get_titles()
{
static titles_map titles;
[...]
return titles;
}
This code is broken. Someone used all the rope given to him by C++ to shoot
himself in the foot. Let me explain...
Static objects (i.e. globals, class-statics) are initialised at startup in
an undefined order. If they depend on each other, what you get is random
erratic behaviour, the so-called initialisation order fiasco (also see the
FAQ):
He reported that the program crashed randomly on startup.
Sometimes it worked sometimes it crashed.
In order to avoid that, you replace such static objects with function-static
objects which are initialised when the function is first called, i.e. an
initialisation on demand. Typically, it is in a function which just returns
a reference to that object like get_titels() above.
Now, the problem here is that someone was trying to be smart and make the
syntax a bit more convenient by simply binding the returnvalue of that
function in a reference. However, doing that he also introduced another
global object which again suffers the undefined initialisation order.
Uli
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]