Re: Globals
On 11/5/2010 12:43 PM, Andrea Crotti wrote:
Victor Bazarov<v.bazarov@comcast.invalid> writes:
string& operator[](string const& idx) { return config[idx]; }
(returns a reference and takes a reference to const).
Ah ok I see, but why return the reference to the string also?
You're assigning to it, aren't you? And you want the assignment to
stick, don't you? So, returning a temporary is OK if you don't care
that the value you assign isn't stored in the map itself and basically
immediately forgotten after the temporary goes away.
Why do you really need a class? Why can't you simply do
extern std::map<std::string,std::string> GLOBALS;
?
Well it would also work, but with a class for example I can initialize
the values from the configuration file directly in the constructor of
the class...
Yes, or you could simply have a static dummy object that would
initialize your map, like so:
int dummy = GLOBALS_initializer_function(); // namespace scope
And fill up your GLOBALS map in that function... Of course, there is
always the static object initialization fiasco you need to worry about.
Make sure no static objects ever use your GLOBALS before it's
constructed (in case you go with the class) or filled in (if you go with
the initialization function).
V
--
I do not respond to top-posted replies, please don't ask