C++11 shared

tech2022-08-30  118

#include<iostream> using namespace std; //share_ptr是带了引用计数的智能指针。 void foo_constant()  {     int* p = new int(3);     std::shared_ptr<int> sptr(p);     std::shared_ptr<int> sptr2(new int(4));     std::shared_ptr<int> sptr3 = sptr2;     std::shared_ptr<int> sptr4 = std::make_shared<int>(5);

    //用同一个p指针同时对两个智能指针初始化,就会出错     int* p1 = new int(4);     {         std::shared_ptr<int> sptr(p1);         {             std::shared_ptr<int>sptr2(p1);         }     }     /*显然出了最里面的作用域之后,sptr2对象就已经释放了,     此时,对于sptr2来说,p的引用计数为0,     所有p被释放,但是实际上sptr还存在,所以再释放sptr时,就会0xc0000005.*/ } class CPerson; class CSon;

class Cperson { public:     Cperson() {

    }

    void Set(std::shared_ptr<CSon> pSon) {         m_pSon = pSon;     }

    ~Cperson() {     }

    std::shared_ptr<CSon> m_pSon; };

class CSon { public:     CSon() {

    }

    void Set(std::shared_ptr<Cperson> pParent) {         m_pParent = pParent;     }

    ~CSon() {     }

    std::shared_ptr<Cperson> m_pParent; }; void testShared() {     //循环的引用,会出现析构异常,     //将任何一处的share_ptr改为weak_ptr即可。     CSon* pSon = new CSon();     Cperson* pPer = new Cperson();

    {         std::shared_ptr<Cperson> shared_Parent(pPer);         std::shared_ptr<CSon> shared_Son(pSon);

        shared_Parent->Set(shared_Son);         shared_Son->Set(shared_Parent);

        printf("pSon : use_count = %d\r\n", shared_Son.use_count());         printf("pPer : use_count = %d\r\n", shared_Parent.use_count());     }

} int main() {     testShared();     foo_constant();      }

最新回复(0)