Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么在局部范围内声明变量,并将其放入范围外可见的向量中?_C++_Scope - Fatal编程技术网

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

C++ 为什么在局部范围内声明变量,并将其放入范围外可见的向量中?,c++,scope,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

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

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();
}
它是否被推到向量上似乎并不重要,leftIndex、rightIndex、p和i都在循环范围之外保持可见。有人能解释一下吗


我使用英特尔C++ 15编译器,优化了禁用。

你在向量中插入完全构造的对象,所以当调用<代码> PuthSubji>代码时,你实际上是复制(或者如果启用的话)对象到向量中的一个新对象。然后,这个新对象的范围与向量的范围相关联。

恐怕我不知道你的意思?你能举个例子吗,你说的“范围外可见”是什么意思?在你的作用域结束后,还有一个变量<代码> RealCuth[/code ]吗?如果这些变量在循环外可见,那么英特尔C++编译器中有一些相当大的错误。你能显示代码,你观察到这些变量在范围之外仍然可见吗?我认为问题在于VisualStudio调试器。在某些特殊情况下,即使循环退出,它也会显示循环内部的所有变量。之前,它实际上保留了这些变量的值并使用它们,即使声明了具有相同名称的新变量,但这一定是一个单独的bug。
CompactPair::CompactPair(long left, long right)
{
    leftSymbol = left;
    rightSymbol = right;
}