zoukankan      html  css  js  c++  java
  • 数组与智能指针

    数组的智能指针的限制

    • unique_ptr 的数组智能指针,没有*-> 操作,但支持下标操作[]。
    • shared_ptr 的数组智能指针,有 *-> 操作,但不支持下标操作[],只能通过 get() 去访问数组的元素。
    • shared_ptr 的数组智能指针,必须要自定义deleter。
    #include <iostream>
    #include <memory>
    #include <vector>
    
    using namespace std;
    
    class test{
    public:
      explicit test(int d = 0) : data(d){cout << "new" << data << endl;}
      ~test(){cout << "del" << data << endl;}
      void fun(){cout << data << endl;}
    public:
      int data;
    };
    

    unique_ptr 与数组:

    int main()
    {
    	unique_ptr<test[]> up(new test[2]);
    	up[0].data = 1;
    	up[1].data = 2;
    	up[0].fun();
    	up[1].fun();
    
    	return 0;
    }
    

    shared_ptr 与数组:

    int main()
    {
    	shared_ptr<test[]> sp(new test[2], [](test *p) { delete[] p; });
    	(sp.get())->data = 2;
    	(sp.get()+1)->data = 3;
    
    	(sp.get())->fun();
    	(sp.get()+1)->fun();
    
    	return 0;
    }
    

    五种智能指针指向数组的方法

    • shared_ptr 与 deleter (函数对象)
    template<typename T>
    struct array_deleter {
    	void operator()(T const* p)
    	{
    		delete[] p;
    	}
    };
    
    std::shared_ptr<int> sp(new int[10], array_deleter<int>());
    
    • shared_ptr 与 deleter (lambda 表达式)
    std::shared_ptr<int> sp(new int[10], [](int* p) {delete[]p; });
    
    • shared_ptr 与 deleter ( std::default_delete)
    std::shared_ptr<int> sp(new int[10], std::default_delete<int[]>());
    
    • 使用 unique_ptr
    std::unique_ptr<int[]> up(new int[10]); //@ unique_ptr 会自动调用 delete[]
    
    • 使用 vector<int>
    typedef std::vector<int> iarray;
    std::shared_ptr<iarray> sp(new iarray(10));
    
  • 相关阅读:
    heapq of python
    array of python
    Unittest of Python
    事件驱动型工作流 vs 引擎型工作流
    airflow
    WPF 调试触发器
    WPF 使用Popup和TreeView实现树状下拉框
    Oracle : ORA 00933: SQL command not properly ended
    PostgreSQL && PostGIS
    基于ArcGIS开发3D立方体空间关系判断
  • 原文地址:https://www.cnblogs.com/xiaojianliu/p/12704192.html
Copyright © 2011-2022 走看看