返回参考后,数据将被删除

Pat*_*ryk 2 c++ reference vector stdvector

我在某种程度上意识到通过引用返回这让我感到困惑.

我有一个返回类的公共领域的引用的功能BoardNode,std::vector<BoardNode> _neighboursVector.

我也有一个类Board,其保持std::vector<BoardNode>.

我的成员函数是这样的:

const std::vector<BoardNode>& 
Board::getNeighboursVector(unsigned int x, unsigned int y) const
{
    BoardNode node = this->getBoardNode(x, y);
    //...
    node._neighboursVector.push_back(...);
    //...
    return node._neighboursVector;
}
Run Code Online (Sandbox Code Playgroud)

在返回行上调试时,我在向量中得到正确的值但在此函数之外我得到空向量.为什么?

std::vector<BoardNode> v = b.getNeighboursVector(5,5);
Run Code Online (Sandbox Code Playgroud)

编辑

getBoardNode 定义

const BoardNode & Board::getBoardNode(unsigned int rowIdx, unsigned int colIdx) const
{
//...
}

BoardNode & Board::getBoardNode(unsigned int rowIdx, unsigned int colIdx)
{
//...
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*ley 6

node是一个本地对象.而且,通过扩展,node._neighborsVector也是一个本地对象.作为本地对象,它在函数结束时被销毁.因此,您将返回对已销毁对象的引用.这是未定义的行为.