这是我第一次实际使用 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/