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;
    }
}
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;
    }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With