首页 > 解决方案 > 为什么我要对这个对象进行大括号初始化(值初始化)以使其成为 constexpr?

问题描述

我想我有一种情况,如果我不支持/值初始化一个对象,它就不能是 constexpr,但我认为它只发生在某些编译器上,这会在 Visual Studio 的“我的”版本上编译:

template <typename T>
struct MyClass
{
    constexpr MyClass() = default;
    

    int member;
};

template <typename T>
constexpr MyClass<T> makeMyClass(T t)
{
    MyClass<T> temp;
           // {}^^^
    // If I keep the constructor and brace-initialise here the error goes away.
    temp.member = 3;
    // Uninitialized variable 'temp' in 'constexpr' function, why do I have to initialise?
    return temp;
}


int main()
{
    constexpr auto myclassobj = makeMyClass(6);
    //^^^ If I add constexpr before this line AND I don't 
    //brace-initialise temp then I get the error: 
    //error: uninitialized variable ‘temp’ in ‘constexpr’ function
}

我在 constexpr 构造函数默认情况下做错了吗?如果我不 { } 大括号初始化,那么它不再是被调用的构造函数了吗?这就是错误吗?如果我不进行大括号初始化,那么它正在调用一个不是 constexpr 的构造函数?

标签: c++constexpr

解决方案


基本问题是您的默认构造函数不能是 constexpr ,因为该类包含int将与默认构造函数保持统一化的 a 。

如果您使用聚合初始化,空大括号表示您对类的成员进行了值初始化,因此该对象已完全初始化,您可以在constexpr表达式中使用它。


推荐阅读