Re: A style question on const char* vs. std::string
Seungbeom Kim wrote:
Ulrich Eckhardt wrote:
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. [...]
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.
So, which exactly is the error? The fact that titles (the data member)
is a reference, not an object?
Yes.
The reference that get_titles() returns is to a static object, which is
initialised at the first call to get_titles() and persists until the end
of the program, and titles (the data member) is a reference to it.. so I
can't see what could be a problem here.
'titles' (the class-static reference) can be accessed before it was
initialised with a call to get_titles(), e.g. from the ctor of another
global[1]. I also typically tend to not treat references as objects, in
particular since it is hard to get things like their size or address, but
they are represented in memory (typically as pointers) and they can be
uninitialised. This is only one of two cases I can think of that it
matters.
In addition, I don't see any "global object" that you say he introduced,
even in class scopes; the only object I see is titles in a local scope.
Hmmm, there is 'transaction_ticket::titles', which is a class-static object
(i.e. suffering the same problems as a global object).
Uli
[1]: 'global' is in fact not the right term but 'object of static duration'
or somesuch, but I haven't finished by first cup of coffee yet...
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]