shared_ptr 和auto_ptr 相同采用的都是RAII 的资源管理方法,即资源获取时初始化,在创建对象的时候获取必要的资源(构造函数)在销毁对象的时候释放资源(析构函数)
auto_ptr 和shared_ptr 的一个区别
std::auto_ptr
和 std::shared_ptr
是 C++ STL 中的两种智能指针,它们都是 RAII 的一种实现方式,用于管理动态分配的内存。但是它们的实现机制和使用方式有所不同。
std::auto_ptr
是一种独占指针,它所指向的资源在一次只能被一个 std::auto_ptr
对象管理。当一个 std::auto_ptr
对象被拷贝或者赋值时,它会自动释放它之前所管理的资源并获取新的资源。这可能导致程序出错。
std::shared_ptr
是一种共享指针,它所指向的资源可以被多个 std::shared_ptr
对象管理。每个 std::shared_ptr
对象都有一个计数器,记录有多少个 std::shared_ptr
对象管理着这个资源。只有当这个计数器为 0 时,资源才会被释放。这样可以避免资源被意外释放的情况。
总结来说,auto_ptr 是一种独占指针,所指向的资源在一次只能被一个 auto_ptr 对象管理。而shared_ptr 是一种共享指针,所指向的资源可以被多个 shared_ptr 对象管理,并且通过计数器来维护资源的生命周期
既然auto_ptr是独占型的一种指针那和unique_ptr 又有什么区别
std::auto_ptr
和 std::unique_ptr
是 C++ 中两种智能指针,它们都是 RAII 的一种实现方式,用于管理动态分配的内存。但是它们的实现机制和使用方式有所不同。
std::auto_ptr
是一种独占指针,它所指向的资源在一次只能被一个 std::auto_ptr
对象管理。当一个 std::auto_ptr
对象被拷贝或者赋值时,它会自动释放它之前所管理的资源并获取新的资源。这可能导致程序出错,因此在 C++11 中被弃用。
std::unique_ptr
是一种独占指针,所指向的资源在一次只能被一个 std::unique_ptr
对象管理。它与 std::auto_ptr
的区别在于,它不能被拷贝,只能被移动。这样就可以避免程序出错的情况。
总结来说,auto_ptr 是一种独占指针,所指向的资源在一次只能被一个 auto_ptr 对象管理,但是它会导致程序出错。而 unique_ptr 是一种独占指针,所指向的资源在一次只能被一个 unique_ptr 对象管理,它可以避免程序出错的情况。
shared_ptr 的一个实现
#include <iostream>
template <typename T>
class shared_ptr_ {
public:
explicit shared_ptr_(T* ptr = nullptr) : m_ptr(ptr), m_count(new int(1)) {}
~shared_ptr_() {
if (--(*m_count) == 0) {
delete m_ptr;
delete m_count;
}
}
shared_ptr_(const shared_ptr_& other) : m_ptr(other.m_ptr), m_count(other.m_count) {
(*m_count)++;
}
shared_ptr_& operator=(const shared_ptr_& other) {
if (this != &other){
if (--(*m_count)==0){
delete m_ptr;
delete m_count;
}
m_ptr = other.m_ptr;
m_count = other.m_count;
(*m_count)++;
}
return *this;
}
T* get() const {return m_ptr;}
int use_count() const {return *m_count; }
private:
T* m_ptr;
int* m_count;
};
int main()
{
shared_ptr_<int> a;
shared_ptr_<int> b(a);
std::cout << a.use_count() << std::endl;
return 0;
}