Copy and swap error warning: recursively on all control paths, the function will cause a stack overflow at runtime

This is the first time I have practically implemented Idiom Copy & Swap. But I am getting this warning when compiling with Microsoft VS2013:

warning C4717: 'std :: swap': recursive on all control path, the function will cause an execution stack overflow

I am trying to get when / where recursion is to blame, but I cannot figure it out. What am I doing wrong. What can be fixed?

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

      

+3


source to share


1 answer


You need to implement your own swap function. std::swap

will invoke the assignment operator. It will cause std::swap

. This will call the assignment operator. What will happen...



class A
{
    // as before

    swap(A& other) { std::swap(m_sp, other.m_sp); }
    A& operator=(A other)
    {
        swap(other);
        return *this;
    }
};

      

+6


source







All Articles