{//通过以下 2 种方式,可以创建出空的 unique_ptr 指针unique_ptr<int>p1(); unique_ptr<int>p2(nullptr);/*创建出了一个 p4 智能指针,其指向的是可容纳 1 个整数的堆存储空间。 和可以用 make_shared<T>() 模板函数初始化 shared_ptr 指针不同,C++11 标准中并没有为 unique_ptr
把shared_ptr设置为nullptr就可以让shared_ptr去释放所管理的裸指针。 类摘要 template<classT>classshared_ptr{public:typedefT element_type;// 内部类型定义shared_ptr();// 构造函数template<classY>explicitshared_ptr(Y * p);template<classY,classD>shared_ptr(Y * p,D d); ~shared_ptr();// 析构...
get()函数,表示返回当前存储的指针(就是被shared_ptr所管理的指针) 。 但是不建议使用get()函数获取 shared_ptr 关联的原始指针,因为如果在 shared_ptr 析构之前手动调用了delete函数,会导致错误 shared_ptr<T> ptr(new T()); T *p = ptr.get(); // 获得传统 C 指针 use_count()函数,表示当前引用计数...
#include<memory>intmain(){// 创建一个unique_ptr,指向一个动态分配的int对象std::unique_ptr<int>ptr(newint(42));// 使用指针操作符和解引用操作符访问所指向对象的值std::cout<<*ptr<<std::endl;// 输出: 42// 通过移动构造函数将所有权转移给另一个unique_ptrstd::unique_ptr<int>ptr2=std::m...
通过gdb可知,拷贝weak_ptr会导致weak_count引用计数增加。 通过下图可更好的理解weak_ptr与shared_ptr的关系 如果令 p = nullptr,则上述结果如下图所示 但控制块对象的生命周期直到weak_count为0时才被彻底清除! 注:若使用make_shared构造智能指针对象,并构造weak_ptr,那么会延迟智能指针所管理资源的释放。(...
{std::cout<<"constructor with no managed object\n";std::shared_ptr<Foo>sh1;bool ok=sh1.get()==nullptr;std::cout<<ok<<'\n';}// copy构造函数的话,引用计数都会增加{std::cout<<"constructor with object\n";std::shared_ptr<Foo>sh2(newFoo);std::shared_ptr<Foo>sh3(sh2);std::...
当两个对象相互持有对方的指针时,可能会形成循环引用,从而导致内存泄漏。为了解决这个问题,我们可以使用 weak_ptr 来代替 shared_ptr。weak_ptr是一种弱引用,它不会增加对象的引用计数,并且在对象释放时会自动设置为nullptr。此外,提供一个自定义的析构函数,也可以帮助我们手动管理对象的生命周期。▲ 创建与初始...
1) 默认构造函数:constexpr shared_ptr() noexcept; 2) 从空指针构造:constexpr shared_ptr(nullptr_t) : shared_ptr() {} 3) 从指针构造:template <class U> explicit shared_ptr (U* p); 4) 从指针 + 删除器构造:template <class U, class D> shared_ptr (U* p, D del);template <class D...
shared_ptr<int> p1(new int (2)); 代码语言:javascript 代码运行次数:0 运行 AI代码解释 SharedPointer(T *ptr = nullptr, const std::function<void(T*)> &del = Deleter()): p(ptr), use_c(new std::size_t(ptr != nullptr)), deleter(del) { } 涉及到的Deleter放在最后来讲。 采用new返回...
obj4=nullptr;//if (obj.unique())//效率更高//if (obj.use_count() == 1)//会有效率损失std::cout<<"only one hold ptr"<< obj.unique() <<std::endl;//值传入print(obj); std::cout<<"ref count is"<< obj.use_count() <<std::endl;//引用传入, 推荐printRef(obj); ...