std::shared_ptr 是一个模板类,用于存储对动态分配对象的引用计数指针。当引用计数降至零时,自动释放所管理的对象。 2. std::shared_ptr 的赋值操作 std::shared_ptr 支持多种赋值方式,包括从另一个 std::shared_ptr 赋值、从裸指针赋值、以及从 std::unique_ptr 赋值(需要 std::move)。
std::shared_ptr<Test> p = std::make_shared<Test>(); std::shared_ptr<Test> p(newTest); (6)std::shared_ptr的大小是原始指针的两倍,因为它的内部有一个原始指针指向资源,同时有个指针指向引用计数。 (7)引用计数是分配在动态分配的,std::shared_ptr支持拷贝,新的指针获可以获取前引用计数个数。 ...
std::weak_ptr是一个与std::shared_ptr相关的类,它不会增加所指向对象的引用计数。即使没有std::shared_ptr实例持有对象,只要存在std::weak_ptr,对象也不会因为引用计数归零而被销毁。但是,一旦所有std::shared_ptr都释放了该对象,std::weak_ptr就会变成过期状态(expired),此时尝试访问对象是不安全的。 (1)创...
7) 从weak_ptr 复制:template <class U> explicit shared_ptr (const weak_ptr<U>& x); 8) 移动构造函数:shared_ptr (shared_ptr&& x) noexcept;template <class U> shared_ptr (shared_ptr<U>&& x) noexcept; 9) 从其他类型的托管指针移动:template <class U> shared_ptr (auto_ptr<U>&& x);t...
在某些情况下,reset可以避免动态内存分配。考虑一下代码
内部维护一个引用计数(reference count)。每当新的shared_ptr拷贝或赋值现有shared_ptr时,引用计数递增;当shared_ptr销毁或重置时,引用计数递减。当引用计数降至零时,自动删除所管理的对象。 支持弱引用计数,通过std::weak_ptr关联到同一对象,但不会增加引用计数。
std::shared_ptr 可以通过 get() 方法来获取原始指针,通过 reset() 来减少一个引用计数, 并通过use_count()来查看一个对象的引用计数。例如: auto pointer = std::make_shared<int>(10); auto pointer2 = pointer; // 引用计数+1 auto pointer3 = pointer; // 引用计数+1 ...
每个std::shared_ptr管理的对象都有一个关联的控制块。这个控制块通常包含以下信息: 引用计数(use_count):跟踪有多少个shared_ptr实例共享同一个对象。每当shared_ptr被复制或赋值时,这个计数会增加;当shared_ptr被销毁或重新赋值时,这个计数会减少。 弱引用计数(weak_count):跟踪有多少个std::weak_ptr实例观察(...
3、赋值操作中,原来资源引用计数会减一,新指向的资源引用计数会加一。 4、线程安全 5、make_shared优于new,make_shared可以一次将需要内存分配好。 6、std::shared_ptr的大小是原始指针的两倍,因为它的内部有一个原始指针指向资源,同时有个指针指向引用计数。
用多个share_ptr指向同一个对象,这多个share_ptr必须有关联,也就是通过智能指针给智能指针赋值,而不是用原始指针。指向同一个对象的share_ptr必须有关联,这样才能对同个对象进行准确的引用计数。 如 {A*p=newA(1);std::shared_ptr<A>p1(p);//p1的usecount为1std::shared_ptr<A>p2(p);//p2的usecount...