Copy&Swap成语警告:在所有控制路径上递归,函数会导致运行时栈溢出

Copy&Swap idiom warning : recursive on all control paths, function will cause runtime stack overflow

这是我第一次实际使用 Copy&Swap 习语。但是我在使用 Microsoft VS2013 编译时收到此警告:

warning C4717: 'std::swap' : recursive on all control paths, function will cause runtime stack overflow

我试图让 when/where 有罪的递归确实发生了,但我无法理解它。 我做错了什么。可以纠正什么?

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;
    }
}

您需要实现自己的交换功能。 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;
    }
};