2017-04-13 36 views
-2

如何克隆弱指針?如何克隆C++中的弱指針對象

class Distance 

{ 

public: 

    int height; 
}; 

main() 
{ 

    weak pointer <Distance> p; 
    p->height = 12; 
    weak pointer <Distance> a; 
    a = p; 
    a->height = 34; 

} 

這裏的時候,A->高度爲10,那麼即使P->高度變成10.我不想對象P的高度可能性。 任何人都可以告訴如何克隆弱指針?

+0

你所說的 「弱指針」 是什麼意思? '的std :: weak_ptr'? – Holt

+0

yes.std :: weak_ptr – Chaya

+0

你不能默認初始化'std :: weak_ptr',並且你不能在'std :: weak_ptr'上使用'p-> whatever',你需要先鎖定它。 'std :: weak_ptr'是指針,與任何指針類型一樣,'a = p;'拷貝指針,而不是指向的內容。如果你想複製內容,你需要'* a = * p;',但是你不能用'weak_ptr'來完成,你需要在''''lock''前鎖定'a'和'p'。 – Holt

回答

1
  1. 您需要初始化併爲p和a找到內存。
  2. 您需要weak_p.lock()在取消引用之前將weak_ptr傳遞給shared_ptr。
  3. 你想要的實際上是深拷貝。在深度複製一個對象之前,您需要定義「複製構造函數」,而不是複製參考點。
  4. weak_ptr不是以這種方式使用,它應該用於當你不理想一個對象是否可用時,這將是另一個話題。

全部例子是

#include <iostream> 
#include <memory> 

using std::weak_ptr; 

class Distance { 
    public : 
    int height; 
    Distance(int h) {height = h;} 
    Distance(const Distance& rhs) { 
     height = rhs.height; 
    } 
}; 

int main() 
{ 
    weak_ptr<Distance> p = std::make_shared<Distance>(12); 
    weak_ptr<Distance> a(p); 
    auto ps = p.lock(); 
    weak_ptr<Distance> b = std::make_shared<Distance>(*ps); 
    auto as = a.lock(); 
    auto bs = b.lock(); 
    std::cout << ps->height << as->height << bs->height << std::endl; 
}