【问题标题】:After returning the reference the data gets erased返回参考后,数据将被删除
【发布时间】:2012-11-23 14:10:33
【问题描述】:

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

我有一个函数,它返回对 BoardNodestd::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)
{
//...
}

【问题讨论】:

  • getBoardNode 是如何声明的?

标签: c++ vector reference stdvector


【解决方案1】:

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

【讨论】:

【解决方案2】:

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

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

【讨论】:

  • 你也不应该将右值引用返回给本地对象。
  • 不能投票给这个答案,因为它建议返回一个指针。
  • @BenjaminLindley 你是对的 - 我已经有一段时间没有玩 move 了。
  • @john:这太荒谬了。 C/C++ 有指针,它是一种语言特性。如果向量的构建时间很长并且有数百万个条目,那么返回指针/智能指针而不是复制的对象会更好。
  • 可能我不够清楚,显然指向的对象必须分配new
猜你喜欢
  • 1970-01-01
  • 2010-10-13
  • 1970-01-01
  • 1970-01-01
  • 2011-07-19
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多