Smart pointers and dynamic arrays

If you want to use smart pointers and arrays, there are different ways of doing it.

std::unique_ptr supports managing dynamic arrays and do not need to write your own deleter:

int main()
{
    int letter{97};
    int size{26};

    unique_ptr<char[]> arr(new char[size]());

    for (int i{}; i != size; ++i)
        arr[i] = static_cast<char>(letter++); // supports subscript

    for (int i{}; i != size; ++i)
        cout << arr[i];
}

You write <char[ ]> notice the empty brackets, to say that it points to an array of char. It will now automatically call delete [] arr when it goes out of scope. It also supports the subscript operator.

While std::shared_ptr does not provide any direct support for managing dynamic arrays, and we have to write our own deleter:

int main()
{
    int letter{97};
    int size{26};

    shared_ptr<char> arr(new char[size](), [](char *p) { delete [] p; });

    for (int i{}; i != size; ++i)
        *(arr.get() + i) = static_cast<char>(letter++);

    for (int i{}; i != size; ++i)
        cout << *(arr.get() + i);
}

Since std::shared_ptr doesn’t have subscript operator and doesn’t support pointer arithmetic, we can use get() to obtain a built in pointer.

Smart pointers and dynamic arrays

Leave a comment