调用 x = std::array<T, N> () 是否与声明 std::array<T, N> x 相同?

Is calling x = std::array<T, N> () same as declaring std::array<T, N> x?

我正在为 class_name 编写自定义移动构造函数和移动赋值运算符。我想知道调用 std::array as std::array<T, N> () 是否正确。

class_name::class_name(class_name&& other) :
    mem_A(std::exchange(other.memA, class_memA())),
    arr_memB(std::exchange(other.arr_memB, std::array<T,N> ()))
{
}
    
class_name& class_name::operator=(class_name&& other)
{
   if (this != other)
   {
      mem_A = mem_A(std::exchange(other.memA, class_memA()));                                                   
      arr_memB = arr_memB(std::exchange(other.arr_memB, std::array<T,N> ()));     
      func_clear();                    
    }
    return *this;
}

是的,您可以使用 array,前提是 arr_memB 是这样声明的。您可以使用 decltype 来避免猜测。

但是在移动赋值运算符中调用 exchange() 时确实需要删除多余的成员名称引用。通过名称调用成员的构造函数仅在构造函数的成员初始化列表中有效。

试试这个:

class_name& class_name::operator=(class_name&& other)
{
    if (this != &other)
    {
        mem_A = std::exchange(other.memA, class_memA());
        arr_memB = std::exchange(other.arr_memB, std::array<T,N>());
        func_clear();
    }
    return *this;
}

或者:

class_name::class_name(class_name&& other) :
    mem_A(std::exchange(other.memA, decltype(mem_A){})),
    arr_memB(std::exchange(other.arr_memB, decltype(arr_memB){}))
{
} 

class_name& class_name::operator=(class_name&& other)
{
    if (this != &other)
    {
        mem_A = std::exchange(other.memA, decltype(mem_A){});
        arr_memB = std::exchange(other.arr_memB, decltype(arr_memB){});
        func_clear();
    }
    return *this;
}