c++ - 为什么在局部范围内声明一个变量,并放入范围外可见的 vector 中?

标签 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;
}

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

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

最佳答案

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

关于c++ - 为什么在局部范围内声明一个变量,并放入范围外可见的 vector 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28984874/

相关文章:

MATLAB 错误? "Undefined function or variable"函数和变量使用相同名称时出错

c++ - "local variables at the outermost scope of the function may not use the same name as any parameter"是什么意思?

python - 装饰器中不同类型的变量是否有不同的作用域? (Python)

c++ - 如何为 double 编写一个包装器以与 boost 序列化一起使用?

c++ - 如何在 meanShiftSegmentation() 输出上运行 findContours()?

c++ - 初学者练习 : Design a Money class

c - C中的静态局部变量地址

javascript - 为什么页面加载时设置的变量在 document.ready 范围内不可用?

c++ - '>>>' Java 到 C++

c++ - 用其他语言编写的函数是否受关于 UB 的 C++ 规则的约束?