My class has methods that return const <Container>&
because I don't want the returned container to be modified outside and copying could be expensive. for Example: const std::set<ClassA>& foo()
and I want foo()
to be able to return a const reference to an empty std::set<ClassA>
if it has to. i.e.
const std::set<ClassA>& foo(const std::string& key) {
std::map<std::string, std::set<ClassA>>::iterator itr = m_elements.find(key);
return (itr != m_elements.end()) ? *itr : /*empty std::set<ClassA>*/;
}
But I cannot really return a const reference to a temporarily constructed empty std::set<ClassA>
in foo()
. To solve this I am defining a generic template singleton class in a common place so that it can be used with any type
template <typename T> class cNull
{
public:
static const T& Value() {
static cNull<T> instance;
return instance.d;
}
private:
cNull() {};
cNull(const cNull<T>& src);
void operator=(cNull<T> const&);
T d;
};
So now foo()
can be something like
const std::set<ClassA>& foo(const std::string& key) {
std::map<std::string, std::set<ClassA>>::iterator itr = m_elements.find(key);
return (itr != m_elements.end()) ? *itr : cNull<std::set<ClassA> >.Value();
}
What I was wondering is, if there's a better way to solve this problem and if there are any issues with this design?