复制和交换习语警告:在所有控制路径上递归,函数将导致运行时堆栈溢出

Ste*_*and 3 c++ compiler-errors

这是我第一次实际使用Copy&Swap成语.但是我在汇编时得到了这个警告,使用Microsoft VS2013:

警告C4717:'std :: swap':在所有控制路径上递归,函数将导致运行时堆栈溢出

我试图得到有罪递归发生的时间/地点,但我无法掌握它.我做错了什么.什么可以纠正?

class A
{
private:
    SmartPtr m_sp = nullptr;

public:
    A(){}

    ~A(){}

    A(const A& other)
    {       
        m_sp = other.m_sp;    
    }

    A(A&& other)
    {
        std::swap(*this, other);
    }

    A& operator=(A other)
    {
        std::swap(other, *this);
        return *this;
    }
}
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 6

您需要实现自己的交换功能.std::swap将调用赋值运算符.哪个会打电话std::swap.这将调用赋值运算符.哪个会......

class A
{
    // as before

    swap(A& other) { std::swap(m_sp, other.m_sp); }
    A& operator=(A other)
    {
        swap(other);
        return *this;
    }
};
Run Code Online (Sandbox Code Playgroud)

  • 并且`std :: swap`也会调用move构造函数,它再次调用`std :: swap`. (3认同)