readability-isolate-declaration

检测声明多个变量的局部变量声明,并尝试将代码重构为每个声明一个语句。

自动代码转换将使用与原始代码相同的缩进,为每个创建的语句添加一个换行符,并保持变量声明的顺序一致。

void f() {
  int * pointer = nullptr, value = 42, * const const_ptr = &value;
  // This declaration will be diagnosed and transformed into:
  // int * pointer = nullptr;
  // int value = 42;
  // int * const const_ptr = &value;
}

该检查排除了在语句中声明多个变量是必要或常见的,并且语言中没有其他支持方法的情况。请注意,结构化绑定不被考虑在内。

// It is not possible to transform this declaration and doing the declaration
// before the loop will increase the scope of the variable 'Begin' and 'End'
// which is undesirable.
for (int Begin = 0, End = 100; Begin < End; ++Begin);
if (int Begin = 42, Result = some_function(Begin); Begin == Result);

// It is not possible to transform this declaration because the result is
// not functionality preserving as 'j' and 'k' would not be part of the
// 'if' statement anymore.
if (SomeCondition())
  int i = 42, j = 43, k = function(i,j);

限制

全局变量和成员变量被排除在外。

该检查目前不支持自动转换成员指针类型。

struct S {
  int a;
  const int b;
  void f() {}
};

void f() {
  // Only a diagnostic message is emitted
  int S::*p = &S::a, S::*const q = &S::a;
}

此外,当检测到语句范围内的各种宏或预处理器指令时,转换非常谨慎。在这种情况下,转换将不会发生,以避免由于宏造成的意外副作用。

#define NULL 0
#define MY_NICE_TYPE int **
#define VAR_NAME(name) name##__LINE__
#define A_BUNCH_OF_VARIABLES int m1 = 42, m2 = 43, m3 = 44;

void macros() {
  int *p1 = NULL, *p2 = NULL;
  // Will be transformed to
  // int *p1 = NULL;
  // int *p2 = NULL;

  MY_NICE_TYPE p3, v1, v2;
  // Won't be transformed, but a diagnostic is emitted.

  int VAR_NAME(v3),
      VAR_NAME(v4),
      VAR_NAME(v5);
  // Won't be transformed, but a diagnostic is emitted.

  A_BUNCH_OF_VARIABLES
  // Won't be transformed, but a diagnostic is emitted.

  int Unconditional,
#if CONFIGURATION
      IfConfigured = 42,
#else
      IfConfigured = 0;
#endif
  // Won't be transformed, but a diagnostic is emitted.
}