非常量左值引用

问题描述 投票:0回答:1

[每次将邻居A添加到节点B时,我都会创建无向图,我也必须将节点B添加为A的邻居,但我的方法不起作用。

Non-const lvalue reference to type 'Element *' cannot bind to a temporary of type 'Element *'

class Element
{
    std::vector<Element *> m_neighbours;
private:

public:
    void addNeighbour(Element*& neighbour)
    {
        m_neighbours.push_back(neighbour);
        neighbour->addNeighbour(this);
    }
};
  1. 发生了什么事?
  2. 解决它的最佳方法?
c++ pointers reference this rvalue
1个回答
0
投票

要了解问题所在,让我们想象一下,您编写了此代码:

void addNeighbour(Element*& neighbour)
{
    m_neighbours.emplace_back(neighbour);
    neighbour->addNeighbour(this);
    neighbour = nullptr; // <--- This is new
}

现在,请考虑拨打此电话时会发生什么:

neighbour->addNeighbour(this);

对该函数的调用通过引用传入this,表示“请随时重新分配this”。然后,在函数调用中,实际上,最后一行试图将neighbour重新分配给nullptr。但这是一个问题,因为您不能写

this = nullptr; // Error!

因为this是右值。

最简单的解决方法是不通过引用获取参数,因为您在实际需要引用的地方不执行任何操作。只需输入Element*,说“请把您感兴趣的指针的副本交给我。”

((独立地-您的代码会给您带来麻烦,因为调用A->addNeighbour(B)会调用B->addNeighbour(A),后者会调用A->addNeighbour(B),又会调用B->addNeighbour(A),以此类推,直到耗尽调用堆栈。您应该添加一个检查在此处确保如果已经录制了Element,则无需第二次添加。为此,您可能希望将m_neighbours设置为std::unordered_set而不是std::vector。) >

© www.soinside.com 2019 - 2024. All rights reserved.