Returning const ref
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.
#include <iostream>
#include <cstdlib>
#include <map>
#include <set>
using namespace std;
class Container
{
public:
void add(size_t i, char c);
const set<char>& get(size_t i) const;
private:
map<size_t, set<char> > content;
};
void Container::add(size_t i, char c)
{
content[i].insert(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())
return empty;
return mit->second;
}
int main()
{
Container c;
c.add(0, 'a');
c.add(0, 'b');
const set<char>& charSet0 = c.get(0);
const set<char>& charSet1 = c.get(1);
cout << charSet0.size() << endl;
cout << charSet1.size() << endl;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]