gpt4 book ai didi

c++ - 我们需要 move 和复制作业吗

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

对于类A,我们可以使用

A& operator=( A other ) { /* ... */ }

代替

A& operator=( const A&  other ) { /* ... */ }
A& operator=( const A&& other ) { /* ... */ }

不会降低性能或其他负面影响?

最佳答案

实际上,您可以通过以下方式实现 copy-and-swap

A& operator=( A other ) { swap(other, *this); return *this; }

对于复制和 move 赋值,但自赋值运算符的无条件复制会降低性能。

Except,上面的函数不能标记为noexcept move 应该是轻量级的,廉价的,它不是必需的,但它应该是轻量级的。因此, move 构造函数/赋值应该是noexcept。没有 noexcept move 构造函数/赋值运算符,move_if_noexcept容器增长时不能调用,容器会回去复制。

因此,推荐的方式是:

A& operator=( const A&  other ) {
if (std::addressof(other) != this) {
A(other).swap(*this); // Copy constructor may throw
}
return *this;
}
A& operator=( A&& other ) noexcept { // note no const here
// we don't check self assignment because
// an object binds to an rvalue reference it is one of two things:
// - A temporary.
// - An object the caller wants you to believe is a temporary.
swap(other);
return *this;
}

关于c++ - 我们需要 move 和复制作业吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40907936/

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