【发布时间】:2011-03-01 15:38:30
【问题描述】:
每天都在尝试学习新的东西,如果以下是好的或坏的设计,我会很感兴趣。
我正在实现一个类A,它将自身的对象缓存在一个静态私有成员变量std::map<> cache 中。 A 的用户应该只能访问指向映射中元素的指针,因为 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())
// ...
};
上面的代码有什么问题吗?有没有什么坑, 我想念内存管理问题还是其他什么?
感谢您的反馈!
【问题讨论】:
-
您说复制 A 很昂贵,但您正在创建 A 然后将其复制到地图中
-
@jimmy:你是对的,但对象必须“生活”在某个地方,对吧?如果我使用
map<int, A*>,谁拥有新的A的所有权?抱歉,如果有明显的答案... -
我倾向于考虑一些描述的智能指针(boost::shared_ptr 可以用于容器)。
-
如果您使用的是支持右值引用的编译器,则给 A 一个移动构造函数将使这成为非问题。