我使用智能指針,並試圖總結我的頭周圍最好使用它盯着。我讀過大量的文章,但我很困惑在下面的例子中使用哪一個。我已經包含了shared_ptr
和unique_ptr
例子來說明什麼,我試圖完成:shared_ptr的VS的unique_ptr使用類和兒童
class A
public:
A();
private:
unique_ptr<B> ptrB;
unique_ptr<SomeObject> ptrUnique;
shared_ptr<SomeObject> ptrShared;
A::A()
{
ptrB(new B());
ptrUnique(new SomeObject());
ptrB->PassUnique(ptrUnique);
ptrShared(new SomeObject());
ptrB->PassShared(ptrShared);
}
class B:
pubic:
void PassUnique(unique_ptr<SomeObject> &ptr_unique);
void PassShared(weak_ptr<SomeObject> &ptr_weak);
void DoSomething();
private:
unique_ptr<SomeObject> ptrUnique;
weak_ptr<SomeObject> ptrWeak;
B::PassUnique(unique_ptr<SomeObject> &ptr_unique)
{
ptrUnique = ptr_unique;
}
B::PassShared(weak_ptr<SomeObject> &ptr_weak)
{
ptrWeak = ptr_weak;
}
B::DoSomething()
{
ptrUnique->SomeMethod();
shared_ptr<SomeObject> ptr1 = ptrWeak.lock();
ptr1->SomeMethod();
}
SomeObject類可以是任何類。一個很好的例子是我從父類A傳遞的數據庫句柄,它最初是由多個類(如B)啓動的,並且從B到C(如果存在)。我的問題是,如果我傳遞一個unique_ptr作爲參考將設置例如ptrUnqiue = ptr_unique
B:PassUnique創建一個副本,然後是不正確的?或者應該通過shared_ptr完成?這種理解與我的智能指針混淆,並希望澄清。
你不能這樣做'ptrUnique = ptr_unique' ..所以你的問題似乎有點空洞。 http://en.cppreference.com/w/cpp/memory/unique_ptr/operator%3D – Default
謝謝我不太確定使用情況。 – adviner