2012-04-10 136 views
4

我有兩個升壓的shared_ptr的如何重新分配升壓shared_ptr的

shared_ptr<X> A(new X); 
shared_ptr<X> B(new X); 

以及最初指向同一個X爲A.

shared_ptr<X> C = A; 

什麼是將C的正確方法第3指針這樣它指向與B相同的X?

C = B; 
+0

你試過了嗎?有什麼不工作?看起來很好。 – loganfsmyth 2012-04-10 17:34:13

+13

如果你只是在尋找確認,是的,'C = B;'是正確的。 – ildjarn 2012-04-10 17:36:00

+2

是的,這將工作,爲什麼不嘗試? – EdChum 2012-04-10 17:39:44

回答

2

EdChm是對的。我已經做了一個小測試程序來明確它。它使用C++ 11,但可以輕鬆轉換。

#include <iostream> 
#include <memory> 

int main() 
{ 
    std::shared_ptr<int> A(new int(1));//creates a shared pointer pointing to an int. So he underlying int is referenced only once 
    std::shared_ptr<int> B(new int(2));//creates another shared pointer pointing to another int (nothing to do with the first one so the underlying int is only referenced once 
    std::shared_ptr<int> C;//creating a shared pointer pointing to nothing 

    std::cout<<"Number of references for A "<< A.use_count()<<std::endl; 
    std::cout<<"A points to "<<*(A.get())<<std::endl; 
    std::cout<<"Number of references for B "<< B.use_count()<<std::endl; 
    std::cout<<"A points to "<<*(B.get())<<std::endl; 
    std::cout<<"Number of references for C "<< C.use_count()<<std::endl; 

    std::cout<<"Now we assign A to C"<<std::endl; 
    C=A; // now two shared_ptr point to the same object 
    std::cout<<"Number of references for A "<< A.use_count()<<std::endl; 
    std::cout<<"A points to "<<*(A.get())<<std::endl; 
    std::cout<<"Number of references for C "<< C.use_count()<<std::endl; 
    std::cout<<"C points to "<<*(C.get())<<std::endl; 

    std::cout<<"Number of references for B "<< B.use_count()<<std::endl; 
    std::cout<<"B points to "<<*(B.get())<<std::endl; 
    return 0; 
} 

這個例子很大程度上受這個環節的啓發。 http://www.cplusplus.com/reference/memory/shared_ptr/shared_ptr/

希望有幫助, 隨時要求更多的細節。