首页 > 解决方案 > 使用部分 NSDMI 聚合 constexpr 默认构造函数错误

问题描述

我在下面有一个简单的结构,用于具有聚合初始化语法的常量表达式。test::c现在,由于NSDMI,我想将其设为可选,但这会在 gcc 和 clang 的常量表达式上下文中触发默认构造函数的错误。

我不明白为什么隐式默认构造函数在第一种情况下默认初始化所有成员,但不使用 NSDMI。如果我为所有成员设置默认值没有错误,但这不是我想要的。此外,我不能声明默认构造函数,因为该结构将不再是聚合。

  1. 在这两种情况下如何隐式生成默认构造函数?有标准规则吗?
  2. 有没有办法修复错误并保存警告[-Wmissing-field-initializers]
#include "debug.h"

struct test {
    //OK
    /* int a, b, c; */
    /* int a=0, b=0, c=3; */
    //ERROR
    int a, b, c=3;
};

int main(){
    const test val1 = test();     //{0,0,3}
    constexpr test val2 = test(); //error: call to non-'constexpr' function 'test::test()'
    constexpr test val3 = {};     //{0,0,3}
    constexpr test val4 = {1};    //warning: missing initializer for member 'test::b'
    constexpr test val5 = {1,2};  //{1,2,3}
}

输出 :

test.cpp: In function 'int main()':
test.cpp:13:32: error: call to non-'constexpr' function 'test::test()'
     constexpr test val2 = test();
                                ^
test.cpp:3:8: note: 'test::test()' is not usable as a 'constexpr' function because:
 struct test {
        ^~~~
test.cpp:8:9: note: defaulted default constructor does not initialize 'int test::a'
     int a, b, c=3;
         ^
test.cpp:8:12: note: defaulted default constructor does not initialize 'int test::b'
     int a, b, c=3;
            ^
test.cpp:15:29: warning: missing initializer for member 'test::b' [-Wmissing-field-initializers]
     constexpr test val4 = {1};
                             ^

谢谢您的帮助。

标签: c++initializationaggregateconstexprdefault-constructor

解决方案


推荐阅读