生成有关错误静态函数使用的编译器警告
Generating a compiler warning on bad static functions usage
我正在维护一个 VS C++ 项目,我经常看到静态成员函数用作 class 方法。
例如:
class A {
public:
static int func(int i);
};
...
A* a = new A();
a->func(3);
...
有没有办法从编译器生成警告,以便我可以像这样清理所有源代码:
...
A::func(3);
...
因为我可以得到未使用和声明的变量的警告,我想应该有类似的东西来处理这些类型的不良成员使用,但没有运气:即使我在编译器选项中设置 /Wall
我没有收到编译器的警告。
编译器不需要给出任何警告,因为对于static
成员方法func()
,以下两个调用都是有效的:
a->func(3); // calling as of it's a non-static member method
A::func(3); // calling as a proper `static` member method
但是,您确定 A::func(3)
对 reader 的信息更丰富,这明确表明 func()
是 static
成员。
"is there a way to generate a warning from the compiler ... ?"
遗憾的是,无法检测不太受欢迎的正确语法。
但是可以进行反编译:
private: static int func(int i); // make `func()` inaccessible outside `class A`
通过给定的 static
方法 private
编译代码。这将在调用 func()
的任何禁止位置产生错误。现在您可以更正它并再次删除 private:
说明符。
这有点乏味,但肯定是射击方式。
您也可以在 "Eclipse-CDT" 等 IDE 中使用 "call hierarchy" 功能,但有可能错过 template
s 或一些棘手的函数调用。
我正在维护一个 VS C++ 项目,我经常看到静态成员函数用作 class 方法。
例如:
class A {
public:
static int func(int i);
};
...
A* a = new A();
a->func(3);
...
有没有办法从编译器生成警告,以便我可以像这样清理所有源代码:
...
A::func(3);
...
因为我可以得到未使用和声明的变量的警告,我想应该有类似的东西来处理这些类型的不良成员使用,但没有运气:即使我在编译器选项中设置 /Wall
我没有收到编译器的警告。
编译器不需要给出任何警告,因为对于static
成员方法func()
,以下两个调用都是有效的:
a->func(3); // calling as of it's a non-static member method
A::func(3); // calling as a proper `static` member method
但是,您确定 A::func(3)
对 reader 的信息更丰富,这明确表明 func()
是 static
成员。
"is there a way to generate a warning from the compiler ... ?"
遗憾的是,无法检测不太受欢迎的正确语法。
但是可以进行反编译:
private: static int func(int i); // make `func()` inaccessible outside `class A`
通过给定的 static
方法 private
编译代码。这将在调用 func()
的任何禁止位置产生错误。现在您可以更正它并再次删除 private:
说明符。
这有点乏味,但肯定是射击方式。
您也可以在 "Eclipse-CDT" 等 IDE 中使用 "call hierarchy" 功能,但有可能错过 template
s 或一些棘手的函数调用。