关于 C++ 对象构造和范围的问题

question on c++ object construction and scope

这有点难以用语言表达,这里是片段,

int main() {
    int i = 5;
    {
        int i(i);
        i = i+5;
//        int i = i;
//        i = i + 5;

        cout << "inner scope" << endl;
        cout << i << endl;
    }
    cout << "outer scope" << endl;
    cout << i << endl;
}

这给出了正确的输出

inner scope
10
outer scope
5

但如果我这样做,

int main() {
    int i = 5;
    {
      //int i(i);
      //i = i+5;
        int i = i;
        i = i + 5;

        cout << "inner scope" << endl;
        cout << i << endl;
    }
    cout << "outer scope" << endl;
    cout << i << endl;
}

这会引发运行时异常,并给出错误的输出,

inner scope
-858993455
outer scope
5

我感觉这好像和拷贝构造函数和赋值构造函数的调用顺序不同有关,但我不是很确定,请赐教。

当你隐藏一个变量时,你会删除它在该范围内的所有痕迹,所以:

int i = i;

这声明 i 等于它的(未初始化的)自身。这个变量完全独立于父作用域的i。这实际上是未定义的行为。

奇怪的是,int i(i) 方法使用父作用域的 i 进行初始化,尽管它的结果很奇怪。虽然它可能没有定义行为。

如果您需要以某种方式将这两者联系起来,您应该使用不同的变量名。如果没有 inter-dependency.

你可以遮蔽

换句话说:

int j = i;