首页 > 解决方案 > 在一个可简单复制的结构中,是否应该实现移动语义?

问题描述

我有这样一个结构:

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() ...

}

我实例化喜欢Dimensions<int>or Dimensions<double>。由于它是可简单复制的,这里最好的策略是什么,生成移动构造函数和移动赋值运算符,= default或者避免隐式运算符= delete

标签: c++c++11templatesc++14move-semantics

解决方案


生成移动构造函数和移动赋值运算符作为= default或避免隐式运算符= delete

前者,除非您希望任何尝试std::move您的类型的代码编译失败。例如

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

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

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

wandbox.org 上的实时示例


推荐阅读