【问题标题】:Rule of 4.5: No move assignment operator?4.5 规则:没有移动赋值运算符?
【发布时间】:2019-01-06 02:49:27
【问题描述】:

基于热门问题What is the copy-and-swap idiom?

  1. 为什么 4.5 的规则不包括移动赋值运算符(实际上成为 5.5 的规则)?相反,我读到(例如,这里What is the Rule of Four (and a half)?)我们的规则是 4.5 还是 5?

  2. 既然swap成员函数是noexcept,那么复制赋值运算符不应该也标记为相同(移动构造函数不能因为它调用可以抛出的默认构造函数)?

dumb_array& operator=(dumb_array other) // should be noexcept?
{
    swap(*this, other);
    return *this;
}

【问题讨论】:

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


    【解决方案1】:

    因为它没有用。

    点击第二个链接,然后点击第四个链接The Rule of The Big Four (and a half) – Move Semantics and Resource Management

    仔细阅读5 - 移动作业部分。

    你会看到

    消除移动赋值运算符

    实际上是移动赋值运算符是不必要的!

    所有的解释!

    本质上,运算符dumb_array& operator=(dumb_array other) 将在您通常使用移动赋值运算符时使用。

    我还没有验证,但你也可以删除它,因为它无论如何都不会生成。

    【讨论】:

    • 谢谢。您能否也澄清一下关于将复制分配设为 noexcept 的第二个问题?
    • noexcept 不应该在那里。 dumb_array other 根据传递的左值或右值构造一个副本或移动一个对象。两者都不是noexcept。
    猜你喜欢
    • 2021-06-08
    • 2017-11-21
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 2020-05-16
    • 2020-12-15
    • 2017-04-19
    • 2015-06-23
    相关资源
    最近更新 更多