Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

It's the first time I practically implement the Copy&Swap idiom. But I get this warning at compilation, with Microsoft VS2013:

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

I try to get when/where the guilty recursion do happen, but I cannot grasp it. What I'm doing wrong. What can be corrected ?

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;
    }
}
like image 599
Stephane Rolland Avatar asked Sep 15 '25 20:09

Stephane Rolland


1 Answers

You need to implement your own swap function. std::swap will call the assignment operator. Which will call std::swap. Which will call the assignment operator. Which will...

class A
{
    // as before

    swap(A& other) { std::swap(m_sp, other.m_sp); }
    A& operator=(A other)
    {
        swap(other);
        return *this;
    }
};
like image 57
juanchopanza Avatar answered Sep 19 '25 07:09

juanchopanza