OGeek|极客世界-中国程序员成长平台

标题: c++ - 延迟局部变量初始化的constexpr函数 [打印本页]

作者: 菜鸟教程小白    时间: 2022-8-3 00:55
标题: c++ - 延迟局部变量初始化的constexpr函数

我正在尝试编写以下形式的constexpr函数:

constexpr int foo(bool cond) {
    int a, b, c;
    if (cond) {
        a = 1;
        b = 2;
        c = 3;
    }
    else {
        a = -1;
        b = -2;
        c = -3;
    }

    return a + b + c;
}

但是,编译器提示我正在使用未初始化的变量,尽管事实上可以保证局部变量的最终初始化。

我可以重写该函数以使用三元运算符,即int a = cond ? 1 : -1;等,但我不希望这样做。有没有办法说服编译器局部变量将被初始化?



Best Answer-推荐答案


However, the compiler complains that I am using an uninitialized variables, despite the fact that the eventual initialization of the local variables is guaranteed.



初始化或不初始化,没有“最终初始化”。并且,对于constexpr函数,在[dcl.constexpr]中有一个要求:

The definition of a constexpr function shall satisfy the following requirements: [...] its function-body shall be = delete, = default, or a compound-statement that does not contain [...] a definition of a variable of non-literal type or of static or thread storage duration or for which no initialization is performed.


constexpr函数中不能包含未初始化的变量,abc适合您。

所以,你可以做什么?您可以将abc初始化为零。这就绕过了这个要求。或者,您可以在a的每个范围内初始化bcif。或者,您可以使用另一个constexpr函数进行求和:
constexpr int f(int a, int b, int c) { return a+b+c; };

constexpr int foo(bool cond) {    
    if (cond) {
        return f(1,2,3);
    }
    else {
        return f(-1,-2,-3);
    }    
}

有很多解决方法。

关于c++ - 延迟局部变量初始化的constexpr函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41509106/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://www.ogeek.cn/) Powered by Discuz! X3.4