是否可以根据参数创建返回对旧项目的引用的构造函数
Is it possible to create constructors that return the reference to the old items, based on parameters?
假设有一个类:
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
,除非您使用此问题建议的技巧之一。
相关文章:
- 如何返回或护理项目清单基于几个类别
- 如何从 std::vector 搜索和返回项目
- 为什么 C++ 中的字符数组返回其项目而不是地址?
- 移动了 QT 项目,重命名文件夹和项目名称,Moc'ing 返回"'-I'之后缺少值"
- 如何从类中返回自定义数组项目并操纵其属性?C
- 从 Freeglut/Opengl 2.1 项目中获取返回值
- 是否可以根据参数创建返回对旧项目的引用的构造函数
- LoadLibrary 永远不会在 Visual Studio 2013 c++ 项目中返回
- 如何返回文件中项目的索引.dat
- OpenGL 项目返回时带有未定义的引用
- 如果要删除的项目不在列表中,如何返回"false"
- C++对象池,它以智能指针的形式提供项目,这些项目在删除时返回到池中
- 欧拉项目任务#8,代码在某个点之后开始返回错误的答案
- C++/Visual Studio - _wgetcwd返回项目文件夹而不是应用程序
- 搜索函数返回相同的,而不考虑二叉搜索树中存在的项目
- 项目 :错误 PRJ0019:工具从 "Performing Pre-Build Event..." 返回错误代码
- 如何在C++中创建一个返回字节数组的函数?Arduino项目
- select()中的c++makefile项目在stdin中的返回速度异常快
- 项目欧拉任务#8在c++中,代码返回错误答案的微妙原因
- C++跟踪一个项目一次,然后返回