毎日何か新しいことを学ぼうとしている私は、次のデザインが良いか悪いか興味があります。
A
それ自体のオブジェクトを static private member variable にキャッシュするクラスを実装していますstd::map<> cache
。のユーザーはA
、マップ内の要素へのポインターにのみアクセスできるようにするA
必要があります。新しいA
は、マップでまだ利用できない場合にのみ作成されますA
。わかりました、ここにいくつかのコードがあります:
class B;
class A {
public:
static A* get_instance(const B & b, int x) {
int hash = A::hash(b,x);
map<int, A>::iterator found = cache.find(hash);
if(found == cache.end())
found = cache.insert(make_pair(hash, A(b,x))).first;
return &(found->second);
}
static int hash(B & b, int x) {
// unique hash function for combination of b and x
}
// ...
private:
A(B & b, int x) : _b(b), _x(x) {
// do some heavy computation, store plenty of results
// in private members
}
static map<int, A> cache;
B _b;
int _x; // added, so A::hash() makes sense (instead of B::hash())
// ...
};
上記のコードに何か問題がありますか? 落とし穴はありますか、メモリ管理の問題などを見逃すことはありませんか?
ご意見ありがとうございます!