Car*_*ijn 7 c++ std wrapper shared-ptr c++11
编辑:完全重新编辑,因为原来是一个非结构化的混乱:)感谢大家的输入到目前为止; 我希望我在下面的文本中使用它.
我正在寻找一个懒惰创建的可共享指针.我有一个假设的大班Thing.事情是巨大的,因此制造成本很高,但是虽然它们在代码中的任何地方使用(共享,经过大量传递,修改,存储供以后使用等),但实际上它们实际上并没有被使用,所以它们实际上是在延迟创建直到实际访问它们是可取的.因此,需要懒惰地创造,并且需要可分享.让我们调用这个封装指针包装器SharedThing.
class SharedThing {
...
Thing* m_pThing;
Thing* operator ->() {
// ensure m_pThing is created
...
// then
return m_pThing
);
}
...
SharedThing pThing;
...
// Myriads of obscure paths taking the pThing to all dark corners
// of the program, some paths not even touching it
...
if (condition) {
pThing->doIt(); // last usage here
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我们已经提出了四种选择:
typedef std::shared_ptr<Thing> SharedThing;
SharedThing newThing() {
return make_shared<Thing>();
}
...
// SharedThing pThing; // pThing points to nullptr, though...
SharedThing pThing(new Thing()); // much better
SharedThing pThing = newThing(); // alternative
Run Code Online (Sandbox Code Playgroud)
第1点和第6点缺乏得分是一个杀手; 没有选择1.
class SharedThing: public shared_ptr<Thing> {};
Run Code Online (Sandbox Code Playgroud)
并覆盖特定成员以确保在取消引用shared_ptr时,它会及时创建Thing.
这个选项优于1并且可能没问题,但看起来很混乱和/或黑客......
class SharedThing {
std::shared_ptr<Thing> m_pThing;
void EnsureThingPresent() {
if (m_pThing == nullptr) m_pThing = std::make_shared<Thing>();
}
public:
SharedThing(): m_pThing(nullptr) {};
Thing* operator ->() {
EnsureThingCreated();
return m_pThing.get();
}
}
Run Code Online (Sandbox Code Playgroud)
并为operator*和const版本添加额外的包装方法.
这个人在4岁时惨遭失败,所以这个也是关闭的.
class SharedThing {
typedef unique_ptr<Thing> UniqueThing;
shared_ptr<UniqueThing> m_pThing;
}
Run Code Online (Sandbox Code Playgroud)
并添加3.1中的所有其他方法
除了建议的性能(但需要测试)之外,这似乎没问题.
class LazyCreatedThing {
Thing* m_pThing;
}
typedef shared_ptr<LazyCreatedThing> SharedThing;
SharedThing makeThing() {
return make_shared<LazyCreatedThing>();
}
Run Code Online (Sandbox Code Playgroud)
并添加各种运算符 - >重载,使LazyCreatedThing看起来像一个东西*
在这里惨败5,这使得这是一个禁忌.
到目前为止最好的选择似乎是3.2; 让我们看看我们还能想出什么!:)
也许我误解了这个问题,但问题就不能这么简单吗?
\n\nclass Factory\n{\nprivate:\n\n std::shared_ptr<My1stType> my1st_ {};\n std::shared_ptr<My2ndType> my2nd_ {};\n std::shared_ptr<My3rdType> my3rd_ {};\n // \xe2\x80\xa6\n\npublic:\n\n std::shared_ptr<My1stType>\n get1st()\n {\n if (!this->my1st_)\n this->my1st_ = std::make_shared<My1stType>(/* \xe2\x80\xa6 */);\n return this->my1st_;\n }\n\n // \xe2\x80\xa6\n};\nRun Code Online (Sandbox Code Playgroud)\n\n然而,如上所示,这不是线程安全的,以防这对您很重要。
\n