c++ - Copy&Swap成语警告: recursive on all control paths,函数会导致运行时栈溢出

标签 c++ compiler-errors

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

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

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

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

关于c++ - Copy&Swap成语警告: recursive on all control paths,函数会导致运行时栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31068813/

相关文章:

c++ - 使用 ocamlbuild 构建 C++ 代码

C++ 用抽象类重载输入

c++ - DH_free 精确行为

java - 按钮 ActionPerfomed 将字符串从 JList 移动到 JList

java - Android ICS 构建失败并出现错误 41

c++ - Process Explorer 中的可拖动十字线如何工作?

c++ - FFmpeg 好像是版本冲突

ios - 使用和不使用协议(protocol)将选择器发送到 id 有什么区别?

c# - 为什么在这种情况下编译器不提示?

c++ - gluTessCallback 错误 C2440