欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > 体验智能指针的强大2

体验智能指针的强大2

2024/10/24 16:30:40 来源:https://blog.csdn.net/qq_35882705/article/details/141500544  浏览:    关键词:体验智能指针的强大2

智能指针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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com