Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++17

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?

like image 641
Carbon Avatar asked Oct 26 '25 06:10

Carbon


1 Answers

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.

like image 116
Nicol Bolas Avatar answered Oct 28 '25 23:10

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!