如何声明在条件块之间持久存在的引用变量

How to declare a reference variable to persist between conditional blocks?

本文关键字:之间 存在 变量 引用 条件 何声明 声明      更新时间:2023-10-16

如果我计划在多个条件块中使用引用变量,我应该如何声明它?例如:

for (i = ...) {
    if (expr_1(i)) {
        // y[idx(i)] only exists when expr_1 is true
        // i.e. idx(i) is a valid index only when expr_1 is true 
        MyType &x = y[idx(i)];  
        ...
    }
    ... // Stuff not dependent on x
    if (expr_2(i)) {   // (expr_2 is such that expr_1 implies expr_2)
        foo(x);        // error, as x not scoped to persist to here
        ...
    }
    ... // More stuff not dependent on x
    if (expr_3(i)) {   // (expr_3 is such that expr_1 implies expr_3)
        bar(x);        // error, as x not scoped to persist to here
        ...
    }
    ... // etc
}

我不能在条件块之外声明它,因为引用变量必须在声明时初始化,但是它引用的变量只存在于条件块中。

这两种方法都适合你吗?

  1. 如果您没有硬性要求使用引用,请尝试使用指针。然后你可以在父作用域中声明它并初始化为NULL。然后在使用前检查not-NULL

  2. 如果MyType是一个对象,你可以让它从定义了isinitialized()的基类派生,然后调用这个。如果MyType是一个标量,那么如果有一个值在该类型的范围内,但超出了该类型所表示的范围,那么使用这样的值来表示"未设置",并执行如下操作:

.

MyType notInitialised(NOT INITIALISED VALUE);
for (i = ...)
{
        MyType &x = expr_1(i) ? y[idx(i)] : notInitialised; 
        // code not needing x
        if (expr_2(i) && x != notInitialised) {
            ...
        }

希望有帮助?