Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a trivially copyable struct shall the move semantics be implemented?

I have such a struct:

template <class T> struct Dimensions
{
    T horizontal{}, vertical{};

    Dimensions() = default;
    Dimensions(const T& horizontal, const T& vertical)
        : horizontal(horizontal), vertical(vertical) {}
    Dimensions(const Dimensions& other) = default;
    Dimensions& operator=(const Dimensions& other) = default;
    Dimensions(Dimensions&& other) = default; // ?
    Dimensions& operator=(Dimensions&& other) = default; // ?
    ~Dimensions() = default;

    // ... + - * / += -= *= areNull() ...

}

which I instantiate like Dimensions<int> or Dimensions<double>. Since it is trivially copyable, what would be the best policy here, generate the move constructor and move assignment operators as = default or avoid the implicit ones by = delete?

like image 369
FrankS101 Avatar asked Sep 19 '25 13:09

FrankS101


1 Answers

generate the move constructor and move assignment operators as = default or avoid the implicit ones by = delete?

The former, unless you want any code that attempts to std::move your type to fail compilation. E.g.

template <typename T>
void foo()
{
    T a;
    T b = std::move(a);
}

struct X
{
    X() = default;
    X(X&&) = delete;
};

int main() { foo<X>(); }

live example on wandbox.org

like image 191
Vittorio Romeo Avatar answered Sep 21 '25 01:09

Vittorio Romeo