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

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

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

如果不是,那为什么呢?删除违约成员是否是一种理想的行为?何时以及多久出现一次这种情况?


详情

我使用的是 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 函数处发出警告会有所帮助。

最佳答案

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

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 定义成员函数,如果它会被删除:

error: defaulting this move assignment operator would delete it after its first declaration NotMoveA & NotMoveA::operator=(NotMoveA &&other) = default;

关于c++ - 删除显式默认函数声明时发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51970117/

相关文章:

c++ - 使用嵌套 vector

html - 是否可以在 Visual Studio C++ 项目中将 Javascript 和 CSS 代码与 HTML 代码分开?

c++ - 为什么 union 的大小不是最大成员的大小?

android - MediaProjectionManagerService 内部抛出 DeadObjectException

java - Eclipse:每个工作区可能有 'Ignore optional compile problems'?

c++ - 避免使用 auto 关键字字面上重复 const 和非常量的代码?

c++ - 如何 boost::serialize std/boost::optional?

c++ - 如果 catch 不执行任何操作,编译器优化会删除 try/catch block 吗?

c++ - std::function 和 lambda 参数的段错误

ios - Xcode出于未知原因给出版本兼容性警告