是否可以根据参数创建返回对旧项目的引用的构造函数

Is it possible to create constructors that return the reference to the old items, based on parameters?

本文关键字:项目 返回 引用 构造函数 创建 参数 是否      更新时间:2023-10-16

假设有一个类:

class X {
    public:
        static X& get_instance(int foo, int bar);
    private:
        X();
        int foo, bar;
}

如果我正确编写了,则get_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 ,必须有更好的方法来做到。

herb sutter最喜欢的10件线,针对略有不同的论点进行了调整并删除锁:

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;
}

由于构造函数是私有的,所以不能使用make_shared,除非您使用此问题建议的技巧之一。