为什么std :: make_unique无法推断括号初始化参数的类型?

时间:2020-02-21 12:09:59

标签: c++ constructor variadic-functions perfect-forwarding list-initialization

请考虑以下代码段

#include <memory>

struct A {
    int x, y;
};

struct B{
    A a;

    B(A a): a(a) {}
};

int main() {
    // Ok
    B({2,3});

    // Ok
    auto ptr = new B({2,3});

    // Ok
    auto ptr_2 = std::make_unique<B>(A{2, 3});

    // Error
    auto ptr_3 = std::make_unique<B>({2, 3});
}

以前两种方式初始化B对象时,可以在不命名类型的情况下创建临时A构造函数参数,并且编译器可以弄清楚其表示什么以及应调用的构造函数。

但是,std::make_unique无法在未显式命名参数类型的情况下编译。根据{{​​3}},该函数调用等效于

unique_ptr<T>(new T(std::forward<Args>(args)...))

我曾期望用std::forward进行的调用等同于new B({2,3});,但在我测试的编译器(即gcc和clang干线)上不是这种情况。他们错了吗?如果没有,为什么转发参数不如我预期的那样?

0 个答案:

没有答案
相关问题