【问题标题】:Warning when an explicitly defaulted function declaration is deleted删除显式默认函数声明时发出警告
【发布时间】:2018-08-22 15:21:25
【问题描述】:

是否有一个诊断标志或工具可以在我有编译器删除的显式默认函数声明时警告我

如果不是,那为什么?被删除的默认成员可以是期望的行为吗?这种情况何时以及多久发生一次?


详情

我使用的是 clang 版本 5.0.1,但通过最近的 MSVC 或 gcc 版本发出警告也可以。

我所拥有的简化示例:

class NotMoveA
{
public:
  explicit NotMoveA(Foo f);
  ~NotMoveA() = default;
  NotMoveA(const NotMoveA &) = delete;
  NotMoveA(NotMoveA &&other) = default;
  NotMoveA &operator=(const NotMoveA &) = delete;
  //will B deleted w/o warning:
  NotMoveA &operator=(NotMoveA &&other) = default; 
  // ...
private:
  const std::string badDataMemberDisallowingMoveAssignment;
  // ...
}

并在std::vector 中使用了NotMoveA。由于NotMoveA 不是MoveAssignable,我遇到了一些错误,这些错误的原因花了我很长时间才弄清楚。直接针对原因的警告,即在已删除的 = default 函数处,会有所帮助。

【问题讨论】:

  • 你用的是什么编译器?
  • 声明主构造函数default 是您需要更正的语法错误。只有默认、复制和移动构造函数可以声明default,非默认构造函数不能。
  • 我怀疑会有编译器警告。被删除的默认成员通常是理想的行为。
  • 感谢 YSC、Xirema 和 @user2079303 (+3)。我已经相应地更新了我的问题。

标签: c++ c++11 warnings compiler-warnings static-analysis


【解决方案1】:

你需要做的是将默认成员的定义移出类:

class NotMoveA
{
public:
  NotMoveA() = default;
  ~NotMoveA() = default;
  NotMoveA(const NotMoveA &) = delete;
  NotMoveA(NotMoveA &&other) = default;
  NotMoveA &operator=(const NotMoveA &) = delete;
  //will B deleted w/o warning:
  NotMoveA &operator=(NotMoveA &&other); 
  // ...
private:
  const std::string badDataMemberDisallowingMoveAssignment;
  // ...
};

NotMoveA & NotMoveA::operator=(NotMoveA &&other) = default;

一旦你将其定义为异常定义,你将得到一个编译器错误,因为你无法通过= default 定义成员函数,如果它会被删除:

错误:默认此移动赋值运算符将在之后删除它 它的第一个 声明 NotMoveA & NotMoveA::operator=(NotMoveA &&other) = default;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多