Re: Returning const ref
On Mar 6, 5:54 pm, Stefan Chrobot <jan...@op.pl> wrote:
This is a simplified version of the class I once wrote. Please comment
on Container::get() method. Is it good, bad, safe, evil? I admit that I
never saw such use of the static keyword and I wonder if it's OK.
I don't want to use pointers. I don't want to throw an exception,
because it's legal for a key to map into an empty set. And finally, I
don't want to store empty objects when there's no need for doing so.
using namespace std;
void add(size_t i, char c);
const set<char>& get(size_t i) const;
map<size_t, set<char> > content;
void Container::add(size_t i, char c)
const set<char>& Container::get(size_t i) const
static const set<char> empty;
map<size_t, set<char> >::const_iterator mit = content.find(i);
if(mit == content.end())
I'd say that it's pretty much a standard solution, at least in
general. To begin with, it's not rare for functions to return a
"default" value when there is no entry, and the static is
perfectly fine for that.
The one thing you might have to what out for is thread safety.
The easiest way to solve that is just to ensure that your get
function is called at least once before threading starts.
Generally, something like:
static bool inited = (Container().get(0), true) ;
in the file where you define Container should be enough to do
James Kanze (GABI Software) email:firstname.lastname@example.org
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]