C++ 是否可以创建基于参数返回对旧项的引用的构造函数?

C++ 是否可以创建基于参数返回对旧项的引用的构造函数?,c++,oop,C++,Oop,假设有一个类: class X { public: static X& get_instance(int foo, int bar); private: X(); int foo, bar; } 如果我写得正确,那么get\u instance是一个命名构造函数。现在我要做的是 让我们创建一个X的实例 X& first = X::get_instance(3, 5); X& second = X::get_

假设有一个类:

class X {
    public:
        static X& get_instance(int foo, int bar);
    private:
        X();
        int foo, bar;
}
如果我写得正确,那么
get\u instance
是一个命名构造函数。现在我要做的是

让我们创建一个X的实例

X& first = X::get_instance(3, 5);
X& second = X::get_instance(4, 6);
X& third = X::get_instance(3, 5);
我想编写
get_instance
,这样当使用相同的参数调用它两次时,它就应该返回对旧实例的引用,而不是创建新实例。当使用参数(3,5)创建的实例全部被删除时,使用(3,5)创建新实例将创建一个新实例

我想象,通过重载相等测试操作符并跟踪构造函数迄今为止创建的每个对象,这是可能的。但是这是C++,必须有更好的方法来做。

,调整稍微不同的参数并删除锁:

static std::shared_ptr<X> X::get_instance(int foo, int bar) {
    static std::map<std::pair<int, int>, std::weak_ptr<X>> cache;

    auto key = std::make_pair(foo, bar);     
    auto sp = cache[key].lock();
    if (!sp) cache[key] = sp = std::shared_ptr<X>(new X(foo, bar)); 
    return sp;
}
static std::shared\u ptr X::get\u实例(intfoo,intbar){
静态std::map缓存;
自动键=标准::生成一对(foo,bar);
auto sp=cache[key].lock();
如果(!sp)cache[key]=sp=std::shared_ptr(新X(foo,bar));
返回sp;
}

不能使用
make_shared
,因为构造函数是私有的,除非你使用上面建议的技巧之一。

你说的“删除”是什么意思?这听起来像是“flyweight模式”。如果是这样,请查看存储a
从参数映射到X