Problems with shared_ptr wrapping a dynamic array

后端 未结 4 1460
遇见更好的自我
遇见更好的自我 2021-01-13 02:08

I wanted to replace some raw pointers in my class with a std::shared_ptr so that I don\'t have to worry when I create copies of that class. But the raw pointers

4条回答
  •  没有蜡笔的小新
    2021-01-13 02:46

    The solution you suggest is possible, but you will lose the size of the array:

    #include 
    #include 
    
    using namespace std;
    
    template shared_ptr make_shared_array(size_t size)
    {
       return shared_ptr(new T[size], default_delete());
    }
    
    struct Foo
    {
      shared_ptr field;
    };
    
    int main()  
    {
      Foo a;
      a.field = make_shared_array(256);
    
     return 0;
    }
    

    What I have done here is to let the array decay into a pointer. As long as the deleter is an array deleter it should behave correctly.

    To prevent this loss of size, and if you cannot use boost::shared_array as suggested, I would suggest to encapsulate this information in your own shared_array class.

提交回复
热议问题