默认noexcept移动语义

时间:2017-01-12 18:59:23

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

我无法理解以下错误背后的原因。

示例代码:

#include <string>

class Message {
private:
  std::string from;
  std::string to;
  std::string message;

public:
  Message() = default;
  Message(Message&&) noexcept = default;
  Message(const Message&) = default;
  Message& operator=(Message&&) noexcept = default;
  Message& operator=(const Message&) = default;

  Message(const std::string& from,
          const std::string& to,
          const std::string& message)
    : from(from),
      to(to),
      message(message)
  { }

  std::string getFrom() const { return from; }
  std::string getTo() const { return to; }
  std::string getMessage() const { return message; }
};

int main() {
  Message m("me", "you", "hello");
  return 0;
}

编译错误:

$ g++ -std=c++11 -Wall noexcept.cpp 
noexcept.cpp:13:12: error: function ‘Message& Message::operator=(Message&&)’ defaulted on its first declaration with an exception-specification that differs from the implicit declaration ‘Message& Message::operator=(Message&&)’
   Message& operator=(Message&&) noexcept = default;

编译器版本:

$ g++ --version
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

只需从默认移动赋值运算符中删除 noexcept 即可编译示例。但我不明白为什么默认移动构造函数允许 noexcept 但默认移动赋值运算符不允许。

任何人都能解释一下吗?

0 个答案:

没有答案
相关问题