代码之家  ›  专栏  ›  技术社区  ›  DaveFar Fabian Barney

删除显式默认函数声明时发出警告

  •  1
  • DaveFar Fabian Barney  · 技术社区  · 6 年前

    是否有诊断标志或工具可以 如果编译器删除了显式默认的函数声明,则警告我 ?

    如果不是,那为什么?被删除的默认成员是否是期望的行为?什么时候和多久发生一次?


    细节

    我正在使用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;
      // ...
    }
    

    使用 NotMoveA 在一个 std::vector 不动 不是可移动的,我犯了一些错误,我花了很长时间才弄清楚原因。直接针对原因的警告,即删除 = default 功能,会有帮助的。

    1 回复  |  直到 6 年前
        1
  •  4
  •   DaveFar Fabian Barney    6 年前

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

    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 如果要删除:

    错误:默认此移动分配运算符将在之后将其删除 它的第一个