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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With