Warning for calling static methods via instance ob

2019-06-16 16:14发布

问题:

I know calling static method via instance object is explicitly allowed.

But if I want to avoid it manually, how can I to be warned when the calling happens? I mean, is there some compiler options (or some special attributes) to check the situation?

I am using Clang, but any other compiler specific features are also welcome.

回答1:

The answer is simply no. As per the other Q & A, the standard requires and permits this behaviour. See n3797 s9.4/2:

A static member s of class X may be referred to using the qualified-id expression X::s; it is not necessary to use the class member access syntax (5.2.5) to refer to a static member. A static member may be referred to using the class member access syntax, in which case the object expression is evaluated.

Given that blunt language, how would any compiler do what you ask?

Perhaps you should be looking for a version of lint instead. I found http://stellar.cleanscape.net/products/cpp/checks.html and error 1705 that might be what you want, and I'm sure there are others.


So the question is why lint, instead of the compiler. There are shades of grey here, but I think compiler warnings are generally reserved for things that are are or could be or might actually be wrong. They might be undefined behaviour, or implementation defined, or places where the compiler does something different than might have been expected. Calling a static method via a pointer is not in that category. It is absolutely a requirement of the standard, and generates exactly the code you would expect.

Compilers are not for enforcing coding standards, there are other tools for that. In the C/C++ Unix world it is historically lint that gives you the capability to detect and complain about violations of coding standards, not the compiler. In the .Net world it has been FxCop, although now Visual Studio does most of the same things. When you want your code to satisfy specific standards you look for a tool that does static code analysis, such as this list here.

If this doesn't answer your question, perhaps you might like to ask another one. As far as this goes, I'm confident that a compiler does the right thing by implementing the standard and not issuing a warning.



回答2:

Using CppDepend and CQlinq you can detect where all static methods are invoked, and after check manually

for example you can execute the following query:



标签: c++ clang