用括号初始化的make_unique [英] make_unique with brace initialization

查看:305
本文介绍了用括号初始化的make_unique的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

https://en.cppreference.com/w/cpp/memory/ unique_ptr / make_unique 写道 std :: make_unique 可以实现为

template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

这不适用于没有构造函数的普通结构。可以将它们初始化,但没有非默认构造函数。示例:

This does not work for plain structs with no constructors. Those can be brace-initialized but don't have a non-default constructor. Example:

#include <memory>
struct point { int x, z; };
int main() { std::make_unique<point>(1, 2); }

对此进行编译将使编译器抱怨缺少2参数的构造函数,这是正确的。

Compiling this will have the compiler complain about lack of a 2-argument constructor, and rightly so.

我想知道,是否有任何技术上的理由不在大括号初始化方面定义函数呢?如

I wonder, is there any technical reason not to define the function in terms of brace initialization instead? As in

template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
    return std::unique_ptr<T>(new T{std::forward<Args>(args)...});
}

那个在上述情况下效果很好

看到大趋势如何倾向于使用括号进行初始化,我认为在该模板中制作括号是规范的选择,但是标准不执行的事实可能表明我缺少了某些东西。

Seeing how the general trend appears to prefer braces for initialization, I would assume making braces in that template would be the canonical choice, but the fact that the standard doesn't do it might be an indication of me missing something.

推荐答案

某些类具有2种初始化样式具有不同的行为。例如,

Some classes have different behavior with the 2 initialization styles. e.g.

std::vector<int> v1(1, 2); // 1 element with value 2
std::vector<int> v2{1, 2}; // 2 elements with value 1 & 2

也许没有足够的理由选择一个偏爱另一个。我认为该标准只是选择一个并明确说明该决定。

There might not be enough reason to choose one prefer to another; I think the standard just choose one and state the decision explicitly.

作为解决方法,您可能希望实现自己的 make_unique 版本。如您所显示,这不是一件艰苦的工作。

As the workaround, you might want to implement your own make_unique version. As you have showed, it's not a hard work.

这篇关于用括号初始化的make_unique的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆