Carbon
Carbon

Reputation: 3943

Why can't I make a unique pointer to an array, when I can make a shared pointer?

The following is invalid:

#include <memory>
#include <iostream>
typedef double zip[10];

int main()
{
    std::unique_ptr<zip> s = std::make_unique<zip>();
    (*s)[0] = 2.0;
    std::cout << (*s)[0] << std::endl;
    return 0;
}

But the following is perfectly valid:

int main()
{
    std::shared_ptr<zip> s = std::make_shared<zip>();
    (*s)[0] = 2.0;
    std::cout << (*s)[0] << std::endl;
    return 0;
}

Why the discrepancy? What am I missing?

Upvotes: 3

Views: 339

Answers (2)

Nicol Bolas
Nicol Bolas

Reputation: 473352

The difference is because shared_ptr may or may not point to an array. Any particular shared_ptr<T> instance might point to a single T or to an array of T.

By contrast, unique_ptr<T> always points to a single T, while unique_ptr<T[]> points to an array of T. It's coded directly in the type itself. So the version that stores arrays has an appropriate operator[] overload, while the other does not.

It should also be noted that shared_ptr::operator[] is a C++17 addition, wheras unique_ptr<T[]>::operator[] has always been there.

Upvotes: 4

adrtam
adrtam

Reputation: 7211

Because make_unique on array of known bound is disallowed. See Why is `make_unique<T[N]>` disallowed? and https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique

Upvotes: 0

Related Questions