为什么不允许`make_unique`?

2024-04-02

Assume namespace std throughout.

C++14 委员会草案 N3690 定义std::make_unique thus:

[n3690: 20.9.1.4]: unique_ptr创建    [unique_ptr.create]

template <class T, class... Args> unique_ptr<T> make_unique(Args&&... args);

1备注:该函数不应参与重载决策,除非T不是一个数组。
2返回:unique_ptr<T>(new T(std::forward<Args>(args)...)).

template <class T> unique_ptr<T> make_unique(size_t n);

3备注:该函数不应参与重载决策,除非T是一个未知边界的数组。
4返回:unique_ptr<T>(new typename remove_extent<T>::type[n]()).

template <class T, class... Args> unspecified make_unique(Args&&...) = delete;

5备注:该函数不应参与重载决策,除非T是一个已知边界的数组。

现在,在我看来,这就像泥浆一样清晰,我认为它需要更多的阐述。但是,除了这个社论评论,我相信我已经解码了每个变体的含义:

  1. template <class T, class... Args> unique_ptr<T> make_unique(Args&&... args);

    您的沼泽标准make_unique对于非数组类型。据推测,“备注”表明某种形式的静态断言或 SFINAE 技巧是为了防止模板在以下情况下成功实例化:T是一个数组类型。

    在较高的层次上,将其视为相当于的智能指针T* ptr = new T(args);.

  2. template <class T> unique_ptr<T> make_unique(size_t n);

    数组类型的变体。创建一个动态分配的数组n × Ts,并将其包裹在一个unique_ptr<T[]>.

    在较高的层次上,将其视为相当于的智能指针T* ptr = new T[n];.

  3. template <class T, class... Args> unspecified make_unique(Args&&...)

    不允许。 ”未指定“ 可能会是unique_ptr<T[N]>.

    否则智能指针将等同于无效指针T[N]* ptr = new (keep_the_dimension_please) (the_dimension_is_constexpr) T[N];.

首先,我说的对吗?如果是这样,第三个函数是怎么回事?

  • 如果它不允许程序员在为每个元素提供构造函数参数时尝试动态分配数组(就像new int[5](args)是不可能的),那么第一个函数无法为数组类型实例化这一事实已经涵盖了这一点,不是吗?

  • 如果它的存在是为了防止添加到像这样的结构的语言中T[N]* ptr = new T[N] (where N是一些constexpr)那么,为什么呢?难道不是完全有可能吗?unique_ptr<T[N]>存在,包装动态分配的块N × T是?这会是一件坏事吗,以至于委员会不遗余力地禁止使用它来创建它make_unique?

Why is make_unique<T[N]>不允许?


引用自原提案 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3588.txt:

T[N]

自 N3485 起,unique_ptr不提供部分专业化T[N]。 然而,用户会强烈地想要写make_unique<T[N]>()。这 这是一个双赢的局面。返回unique_ptr<T[N]>会选择主要的 单个对象的模板,这很奇怪。返回unique_ptr<T[]>将是铁定规则的一个例外make_unique<something>()回报unique_ptr<something>。因此,这 提案提出T[N]这里格式不正确,允许实现发出 有帮助的static_assert消息。

该提案的作者 Stephan T. Lavavej 在这个关于 Core C++ 的视频 http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/STLCCSeries6(由chris https://stackoverflow.com/users/962089/chris),从 1:01:10 分钟开始(或多或少)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么不允许`make_unique`? 的相关文章

随机推荐