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

Warning when an explicitly defaulted function declaration is deleted

本文关键字:警告 声明 函数 默认 删除      更新时间:2023-10-16

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

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


我使用的是 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不是可移动的,我遇到了一些错误,我花了很长时间才弄清楚其原因。直接针对原因(即已删除= default功能(发出警告会有所帮助。

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

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;