我认为下面的代码比copy-and-swap idiom更好。可以安全地使用复制/移动ctors来实现复制/移动赋值操作符吗?
通过这种方式,你可以用两个宏来封装副本的定义和移动赋值运算符。换句话说,您可以避免在代码中明确定义它们。因此,您只能将注意力集中在ctors和dtor上。
是否有方法的任何不利?
class A
{
public:
A() noexcept
: _buf(new char[128])
{}
~A() noexcept
{
if (_buf)
{
delete[] _buf;
_buf = nullptr;
}
}
A(const A& other) noexcept
: A()
{
for (int i = 0; i < 128; ++i)
{
_buf[i] = other._buf[i];
}
}
A(A&& other) noexcept
: _buf(other._buf)
{
_buf = nullptr;
}
A& operator =(const A& other) noexcept
{
if (this != &other)
{
this->~A();
new(this) A(other);
}
return *this;
}
A& operator =(A&& other) noexcept
{
if (this != &other)
{
this->~A();
new(this) A(static_cast<A&&>(other));
}
return *this;
}
private:
char* _buf;
};
你的默认构造函数'noexcept'究竟如何?而你的移动构造函数不会移动任何东西。在删除某物之前,不需要检查'nullptr'。为什么'static_cast '而不是'std :: move'? – Praetorian
_buf(other._buf)等._buf = nullptr;只是移动操作。 – xmllmx
'static_cast '可用于某些标准库无法使用的环境。所以它比'std :: move'更加兼容。 – xmllmx