Search code examples
c++stdarray

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


I am writing custom move constructor and move assignment operator for class_name. I would like to know if calling std::array as std::array<T, N> () is correct or not.

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;
}

Solution

  • Yes, your use of array is fine, provided that is how arr_memB is declared to begin with. You could use decltype instead to avoid guessing.

    But you do need to remove the redundant member name references when calling exchange() in the move assignment operator. Calling a member's constructor by its name works only in a constructor's member initialization list.

    Try this:

    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;
    }
    

    Alternatively:

    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;
    }