-1

Duplicate as shared_ptr to an array : should it be used?


According to this post, the good way to wrap a array with smart_ptr is to define a deleter function and pass the deleter function to smart_ptr alone with raw arrays.


I'm going to refactor my code, like wrap raw arrays with smart_ptr. Here's a example:

Original codes:

    class MyList{
    public:
       MyList(int size = 0);
       void Resize(int size);
       ~MyList();
    private:
       int* myArray; 
       int* head_;
       size_t size_;
    }

    MyList::MyList(int size){
        myArray = new int[size]; //allocated memory when object is being created 
        head_ = list_;
        size_ = size;
    }

    void MyList::Resize(int size) {
        if (!list_) {
             delete myArray;
             size_ = 0;
        }
        myArray = new int[size];
        head_ = list_;
        size_ = size;
    }

    MyList::~MyList(){
       delete myArray;
       head = null_ptr;
    }  

My question is: How to correctly wrap raw arrays with smart_ptr?

Community
  • 1
  • 1
Charles Chow
  • 1,027
  • 12
  • 26

1 Answers1

6

Don't use shared_ptr as your default smart pointer.

Thats unique_ptr. shared_ptr corresponds to shared ownership. You want unique ownership.

More information here.


Reassignment of smart pointers

Smart pointers are not assignable to raw pointers. That has good reasons.

Instead, write

myArray = std::make_shared<int>( myArraySize );
// Creates ONE int-object, which is initialized to myArraySize

Or use the initialization list directly:

myClass::myClass(int myArraySize) :
    myArray{ std::make_shared<int>(myArraySize) } {}

But you want an array!

Firstly, you should use std::size_t for specifying array bounds.

Now to the actual code for setting up the right smart pointer and initializing it:

std::unique_ptr<int[]> myArray;

// [...]

myClass::myClass(int myArraySize) :
    myArray{ new int[myArraySize]() } {}
    // value-initialized it

Or since C++1y (or with an own definition) with make_unique:

myClass::myClass(int myArraySize) :
    myArray{ std::make_unique<int[]>(myArraySize) } {}
Community
  • 1
  • 1
Columbo
  • 60,038
  • 8
  • 155
  • 203