gpt4 book ai didi

c++ - 在一个普通的可复制结构中, move 语义应该被实现吗?

转载 作者:太空狗 更新时间:2023-10-29 20:51:18 25 4
gpt4 key购买 nike

我有这样一个结构:

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 避免隐式的?

最佳答案

generate the move constructor and move assignment operators as = default or avoid the implicit ones by = 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

关于c++ - 在一个普通的可复制结构中, move 语义应该被实现吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50759544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com