c – 如何重新分配boost shared_ptr
发布时间:2020-12-16 07:29:54 所属栏目:百科 来源:网络整理
导读:我有两个Boost shared_ptr shared_ptrX A(new X);shared_ptrX B(new X); 并且第三个指针最初指向与A相同的X. shared_ptrX C = A; 更改C的正确方法是什么,它指向与B相同的X? C = B; 解决方法 EdChm是对的.我做了一个小测试程序来明确它. 它使用C 11但可以轻
我有两个Boost shared_ptr
shared_ptr<X> A(new X); shared_ptr<X> B(new X); 并且第三个指针最初指向与A相同的X. shared_ptr<X> C = A; 更改C的正确方法是什么,它指向与B相同的X? C = B; 解决方法
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; } 这个例子很大程度上来自于这个链接. 希望有所帮助,随意询问更多细节. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |