返回引用后,数据将被删除

After returning the reference the data gets erased

本文关键字:删除 数据 引用 返回      更新时间:2023-10-16

我不知何故意识到通过引用返回这让我感到困惑。

我有一个函数,它返回对类 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;
}

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

std::vector<BoardNode> v = b.getNeighboursVector(5,5);

编辑

getBoardNode定义

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

node是一个本地对象。 推而广之,node._neighborsVector也是一个本地对象。 作为本地对象,它在函数结束时被销毁。 因此,您正在返回对已销毁对象的引用。 这是未定义的行为。

node

堆栈(函数的本地)上创建,因此在函数结束时删除。由于您返回的引用是 node 字段,因此也会被删除。因此,返回对已删除对象的引用。

您应该按值返回(在这种情况下正确实现复制构造函数 - 这里std::vector没关系)或指针返回(由 new 创建,不要忘记在完成返回对象时delete)。