std::weak_ptr是一种智能指针,它持有被std::shared_ptr管理的对象的非拥有性“弱”引用。在访问引用的对象前必须先转换为std::shared_ptr。 std::weak_ptr实现临时所有权:当某个对象只有存在时才需要被访问,且随时可能被他人删除时,可以使用std::weak_ptr来跟踪该对象,需要获得临时所有权时,将其转换为std::...
std::weak_ptr可以作为std::shared_ptr的构造函数参数,但如果std::weak_ptr指向的对象已经被释放,那么std::shared_ptr的构造函数会抛出std::bad_weak_ptr异常。 std::shared_ptr<int>sp1(newint(22));std::weak_ptr<int> wp = sp1;// point to sp1std::shared_ptr<int>sp2(wp);std::cout<<sp2.us...
std::weak_ptr<T>::weak_ptr constexprweak_ptr()noexcept; (1)(since C++11) weak_ptr(constweak_ptr&r)noexcept; (2)(since C++11) template<classY> weak_ptr(constweak_ptr<Y>&r)noexcept; (2)(since C++11) template<classY> weak_ptr(conststd::shared_ptr<Y>&r)noexcept; ...
std::bad_weak_ptr::operator= bad_weak_ptr& operator=( const bad_weak_ptr& other ) noexcept; (C++11 起) 以other 的内容赋值。如果 *this 与other 均拥有动态类型 std::bad_weak_ptr,那么赋值后 std::strcmp(what(), other.what()) == 0。 参数 other - 用来赋值的另一异常对象 返回值...
1.1 weak_ptr 参考:https://zh.cppreference.com/w/cpp/memory/weak_ptr std::weak_ptr是一种智能指针,它对被std::shared_ptr管理的对象存在非拥有性(“弱”)引用。在访问所引用的对象前必须先转换为std::shared_ptr。 std::weak_ptr用来表达临时所有权的概念: ...
#include <iostream>#include <memory>std::weak_ptr<int>gw;voidf(){if(!gw.expired())std::cout<<"gw is valid\n";elsestd::cout<<"gw is expired\n";}intmain(){{autosp=std::make_shared<int>(42);gw=sp;f();}f();} Output: ...
1.1 weak_ptr 参考:https://zh.cppreference.com/w/cpp/memory/weak_ptr std::weak_ptr是一种智能指针,它对被std::shared_ptr管理的对象存在非拥有性(“弱”)引用。在访问所引用的对象前必须先转换为std::shared_ptr。 std::weak_ptr用来表达临时所有权的概念: ...
shared_ptr的作用主要是在最后一个指向资源的shared_ptr销毁时自动释放资源,然而在某些场景下这种行为可能不被期望。例如: 两个或者多个对象都使用shared_ptr,并且相互通过shared_ptr指向对方,如果存在一个环路(cyclic reference),那么由于环路上的shared_ptr的use_count最终无法降为0,所以环路上的资源将无法被释放。
写一个程序来验证 shared_ptr 内存模型 https://gitee.com/chjfth/trivials/blob/master/cpp/see_shared_ptr/see_shared_ptr.cpp #include<stdio.h>#include<string>#include<memory>usingnamespacestd;intptr_diff(void*p1,void*p2){return(int)((char*)p1-(char*)p2);}voidtest1(){string*pNico2=new...
最后一个指向该对象的shared_ptr被使用operator()=或者reset()重新赋值。 通过查看源代码或者cppreference我们可以看到其中的内容 内部typedef 两个typedef一个叫做element_type,一个叫做weak_type。 在C++17之前,element_type就是你传入的模板T。 在C++17之后,element_type是std::remove_extent<T>。