代码之家  ›  专栏  ›  技术社区  ›  FrankS101

在一个简单的可复制结构中,是否应该实现移动语义?

  •  3
  • FrankS101  · 技术社区  · 8 年前

    我有这样一个结构:

    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> Dimensions<double> . 既然是 trivially copyable ,这里的最佳策略是什么,将move构造函数和move赋值运算符生成为 = default 或者通过 = delete ?

    1 回复  |  直到 8 年前
        1
  •  4
  •   Vittorio Romeo    8 年前

    将move构造函数和move赋值运算符生成为 = 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>(); }
    

    live example on wandbox.org