为什么在本地范围内声明变量,并将其放入范围外可见的向量中?

时间:2015-03-11 11:02:18

标签: c++ scope

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

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编译器并禁用了优化。

1 个答案:

答案 0 :(得分:2)

您正在向量中插入完全构造的对象,因此在调用push_back时,您实际上正在将对象复制(或移动(如果已启用))到位于向量中的新对象。然后将这个新对象的范围绑定到向量之一。