为什么变量在局部范围内声明,并放入范围外可见的向量中

Why is a variable declared in a local scope, and put into a vector visible outside the scope?

本文关键字:范围 向量 局部 变量 范围内 声明 为什么      更新时间:2023-10-16

我的问题是关于以下代码段的:

pairVectors.push_back(new vector<CompactPair>());
for (int i = 0; i < generationVectors[0].size(); ++(i))
{
    //Find the new indices of the two symbols in this pair
    long leftIndex = ((terminalIndices)[(generationVectors[0])[i].leftSymbol]);
    long rightIndex = ((terminalIndices)[(generationVectors[0])[i].rightSymbol]);
    //Make a pair out of the indices we found, then push it to the vector
    CompactPair p(leftIndex, rightIndex);
    pairVectors[0]->push_back(p);

    //Record the index of this symbol
    if (indices[(generationVectors[0])[i].leftSymbol].empty())
    {
        indices[(generationVectors[0])[i].leftSymbol].set_empty_key(-1);
        indices[(generationVectors[0])[i].leftSymbol].set_deleted_key(-2);
    }
    ((indices)[(generationVectors[0])[i].leftSymbol])[(generationVectors[0])[i].rightSymbol] = i + terminals.size();
}

CompactPair p 是使用以下构造函数创建的:

CompactPair::CompactPair(long left, long right)
{
    leftSymbol = left;
    rightSymbol = right;
}

它是否被推到向量上似乎并不重要,leftIndex、rightIndex、p 和 i 都在循环范围之外保持可见。有人能解释一下吗?

我正在使用禁用优化的英特尔 c++ 15.0 编译器。

您在向量中插入完全构造的对象,因此在调用 push_back 时,您实际上是将对象复制(或移动,如果启用)到位于向量中的新对象。然后,这个新对象的作用域与其中一个向量相关联。