I’ve got a “design” problem in a C++ project.
I have a class, named Currency (which can be "USD", "EUR", and so on…, and got some methods)
There are many instances of this class new-ed everywhere in the project, but there can only be a bunch of different currencies (~100).
So I wrote a method which allocates a Currency the first time it’s asked, and returns an existing Currency otherwise :
class Currency
{
public:
typedef std::map<std::string, Currency*> CurrencyMap_t;
public:
static CurrencyMap_t _currencies;
public:
static const Currency& getCcy(const std::string& name)
{
CurrencyMap_t::const_iterator it(_currencies.find(name));
if (it == _currencies.end())
it = _currencies.insert(std::make_pair(name, new Currency(name))).first;
return *(it->second);
}
private:
// can't instantiate from outside
Currency();
Currency(const Currency& other);
private:
// private ctor
explicit Currency(const std::string& name) {... }
};
So, now, I only have one instance of each different Currency.
But, I can’t anymore have a class holding a Currency member, because the default-constructor is not defined :
class CcyPair
{
public:
CcyPair(const Currency& ccy1, const Currency& ccy2) {}
private:
Currency _ccy1; // won't compile because "no default-constructor available"
Currency _ccy2;
};
And I don’t want to hold Currency pointers in CcyPair class.
Do you have a better way to implement such a “pattern” which ensures that if two instances of a class (here the Currency class) got the same attributes, then it’s in fact the same instance (same underlying reference) ?
I know you said you did not want to hold pointers to the Currency objects, but how would you feel about holding a reference instead? I’m not sure if you wanted to avoid pointers so you wouldn’t be burdened by a lot of checks against NULL or if you had another reason. Here is an example CcyPair using references: