智能指针2
- 不带计数的智能指针
-
auto_ptr
: 转移对象的所有权,导致前对象内部指针被置为nullptr
-
scoped_ptr
删除了拷贝构造和赋值运算符
scoped_ptr<T>(const scoped_ptr<T>&) = delete;
scoped_ptr<T>& operator=(cosnt scoped_ptr<T>&) = delete;
-
unique_ptr
删除左值拷贝构造函数和左值赋值运算符
增加右值拷贝构造函数和右值赋值运算符
unique_ptr<T>(const unique_ptr<T>&) = delete;unique_ptr<T>& operator=(const unique_ptr<T>&) = delete;unique_ptr<T>(unique_ptr<T>&&);unique_ptr<T>& operator=(unique_ptr<T>&&);typename<typename T>unique_ptr<T> getSmartPtr{unique_ptr<T> ptr(new T());return ptr; // 临时对象,右值}unique_ptr<T> ptr = getSmartPtr(); // 调用右值拷贝构造函数ptr = getSmartPtr(); // 调用右值赋值运算符
# include <iostream>
# include <memory>/*不带引用计数的智能指针auto_ptr: 转移对象的所有权,导致前对象内部指针被置为nullptrscoped_ptr删除了拷贝构造和赋值运算符scoped_ptr<T>(const scoped_ptr<T>&) = delete;scoped_ptr<T>& operator=(cosnt scoped_ptr<T>&) = delete;unique_ptr删除左值拷贝构造函数和左值赋值运算符增加右值拷贝构造函数和右值赋值运算符unique_ptr<T>(const unique_ptr<T>&) = delete;unique_ptr<T>& operator=(const unique_ptr<T>&) = delete;unique_ptr<T>(unique_ptr<T>&&);unique_ptr<T>& operator=(unique_ptr<T>&&);typename<typename T>unique_ptr<T> getSmartPtr{unique_ptr<T> ptr(new T());return ptr; // 临时对象,右值}unique_ptr<T> ptr = getSmartPtr(); // 调用右值拷贝构造函数ptr = getSmartPtr(); // 调用右值赋值运算符*/
template<typename T>
class SmartPtr{
public:SmartPtr<T>(T* ptr): m_ptr(ptr) {}~SmartPtr<T>() = default;SmartPtr<T> (const SmartPtr<T>&) = delete;SmartPtr<T>& operator=(const SmartPtr<T>&) = delete;T& operator*() {return *m_ptr;}T* operator->() {return m_ptr;}private:T* m_ptr;
};int main()
{// Q1:浅拷贝,造成堆区内存重复释放// SmartPtr<int> ptr(new int);// SmartPtr<int> ptr2(ptr);// *ptr2 = 20;// std::cout << (*ptr) << std::endl;// Q2:auto_ptr auto_ptr转移所有权,导致之前的对象指向nullptr// std::auto_ptr<int> ptr(new int);// std::auto_ptr<int> ptr2(ptr);// *ptr2 = 20;// std::cout << (*ptr) << std::endl;// Q3:scoped_ptr 删除了拷贝构造和赋值运算符// std::scoped_ptr<int> ptr(new int);// std::scoped_ptr<int> ptr2(ptr);// Q4:unique_ptr 删除拷贝构造函数和赋值运算符,加入了右值拷贝构造和右值赋值运算符std::unique_ptr<int> ptr(new int);std::unique_ptr<int> ptr2(std::move(ptr));return 0;
}