返回引用后,数据将被删除
After returning the reference the data gets erased
我不知何故意识到通过引用返回这让我感到困惑。
我有一个函数,它返回对类 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
)。
相关文章:
- 从 Typedef 数据类型中删除常量
- 从输入中删除重复项,而不使用任何数据结构
- 删除使数据处于"错误状态"的默认构造函数的模式?
- 从自定义数据类型向量中删除重复元素
- 如何使用C++删除/更新txt文件中的特定数据
- 如何使用C++删除/更新txt文件中的特定数据?
- 如何从 txt 文件中删除数据/内容
- 如何根据偏移从文件中删除数据
- 如何在返回一次数据后从类实例中删除数据
- 凯撒密码删除数据
- Winsock:从套接字中删除数据
- 为什么我的矢量删除数据
- 设置/删除窗口子类时,正确传递/删除数据
- 双重删除数据不会崩溃
- 具有非常快速的内>数据查找和快速反向查找(搜索/插入/删除数据)的压缩字典?
- 当构造函数抛出异常时,如何删除数据成员的内存
- 从节点中删除数据
- 仅重定向子进程stdin,并从stdout和stderr中删除数据
- 删除数据文件中的条目
- 从链表中删除数据