简体   繁体   English

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

[英]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> . 我实例化了Dimensions<int>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 ? 由于它是可以轻易复制的 ,这里最好的策略是什么,生成移动构造函数并将赋值运算符移动为= default或者通过= delete避免隐式运算符?

generate the move constructor and move assignment operators as = default or avoid the implicit ones by = delete ? 生成移动构造函数并将赋值运算符移动为= default或通过= delete避免隐式运算符?

The former, unless you want any code that attempts to std::move your type to fail compilation. 前者,除非你想要任何试图std::move你的类型以使编译失败的代码。 Eg 例如

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 wandbox.org上的实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 显式默认的move构造函数使该结构不容易复制 - Explicitly defaulted move constructor makes the struct not trivially copyable 少量移动但不可复制 - trivially moveable but not trivially copyable __is_trivially_copyable 如何在 g++ stl 中实现? - how __is_trivially_copyable is implemented inside g++ stl? is_trivially_copyable 在我实现的构造函数和默认构造函数之间的行为不同 - is_trivially_copyable behaves differently between the constructor I implemented and the default 将值分配给必须是可平凡复制的 volatile 结构 - Assign a value to a volatile struct that must be trivially-copyable 在防御上将std :: move应用于平凡可复制的类型是否不受欢迎? - Is it undesirable to defensively apply std::move to trivially-copyable types? const int [2]可以简单地复制吗? - Is const int[2] trivially copyable? 为什么 T[] 可以简单地复制但不能简单地破坏? - Why is T[] trivially copyable but not trivially destructible? std :: is_trivially_copyable - 为什么volatile标量类型不能轻易复制? - std::is_trivially_copyable - Why are volatile scalar types not trivially copyable? 如果包含的类型是一个简单的可复制类型,那么std :: optional是一个简单的可复制类型 - Will std::optional be a trivially copyable type if the contained type is a trivially copyable type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM