为什么不再允许从数组的 unique_ptr 创建 shared_ptr?

Why is creating shared_ptr from unique_ptr of array not allowed anymore?

来自 cppreference:

In C++11 and C++14 it is valid to construct a std::shared_ptr<T> from a std::unique_ptr<T[]>:

std::unique_ptr<int[]> arr(new int[1]);
std::shared_ptr<int> ptr(std::move(arr));

Since the shared_ptr obtains its deleter (a std::default_delete<T[]> object) from the unique_ptr, the array will be correctly deallocated.

This is no longer allowed in C++17. Instead the array form std::shared_ptr<T[]> should be used.

为什么在 C++17 中不允许?发生了什么变化?

p0497r0:

Incorrect constraint for shared_ptr construction from unique_ptr

[...]

Based on implementation experience I believe the correct form is:

        Remark: This constructor shall not participate in overload resolution unless Y* is compatible with T* and unique_ptr<Y, D>::pointer is convertible to element_type*.

The "compatible with" check prevents undesirable conversions from unique_ptr<T[]> to shared_ptr<T> and the "convertible to" check ensures that the result of unique_ptr<Y, D>::get() can be stored in the shared_ptr and returned by shared_ptr<T>::get().

换句话说,这是故意使其无效只是因为它不应该有效,而不仅仅是其他更改的副作用。

这对我来说很有意义。 shared_ptr<T> 很可能被其他程序员解读为仅指向一个 T 对象。要求程序员在需要多个 T 对象时使用 shared_ptr<T[]> 会导致代码更具可读性。

注意:这个正确的形式不在标准中。然而,基本原理部分是对标准内容的评论。