Re: A style question on const char* vs. std::string
On 2006-12-08, James Kanze <james.kanze@gmail.com> wrote:
Just a question, but would it make sense for the object to be
const. (I typically use something like this for mapping enum
Yes, it would.
Ask them what happens if the object is to be used in the
constructor of a static object:-). (In fact, my normal
Funny you should mention that :) The problem originator (not the person I
was arguing with) attempted to to something like the following:
enum tran_type { ... };
typedef std::map<tran_type, const char*> titles_map;
// he's using class as a namespace for static members
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;
static bool titles_initialized = false;
if(!titles_initialized)
{
titles_initialized = true;
// fill the map with code like
titles[..] = "...";
}
return titles;
}
He reported that the program crashed randomly on startup. Sometimes it
worked sometimes it crashed. I have two questions:
1. Why does the assignment marked with [*] compile? I would have expected
that the function call must be transaction_ticket::get_titles().
2. Crashing is probably due to static initialization order. But where
exactly? [Maybe the fact that transaction_ticket::titles reference and
titles (inside get_titles function) are both static? If the reference
gets initialized before static variable in the get_titles() function
is constructed?]
Thanks for your time.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]