C ++ - why a static member function cannot be created using the qualifier 'const'

Today I have a problem. I need a static member function, const not necessary, but better. But I failed in my efforts. Can anyone say why and how?

+70
c ++ language-lawyer static
Aug 12 2018-11-11T00:
source share
5 answers

When you apply the const qualifier to a non-static member function, it affects the this pointer. For a constant member function of class C the this pointer is of type C const* , while for a member function that is not constant, the this pointer is of type C* .

A static member function does not have a this pointer (such a function is not called on a specific instance of the class), so the const criterion of a static member function does not make any sense.

+116
Aug 12 2018-11-11T00:
source share

I agree with your question, but unfortunately C ++ is designed that way. For example:

 class A { int i; //<--- accessed with 'this' static int s; //<---- accessed without 'this' public: static void foo () const // <-- imaginary const {} }; 

Today const considered in the context of this . In a way, it is narrowed. This can be made wider by applying this const pointer outside of this .
that is, the "suggested" const , which can also be applied to static functions, will limit the members of static from any modification.

In the code example, if foo() can be made const , then in this function A::s cannot be changed. I do not see any language side effects if this rule is added to the standard. On the contrary, it’s funny why such a rule does not exist!

+20
Aug 12 2018-11-11T00:
source share

Without going into details, this is because an object may or may not be modified by a function, so const is ambiguous for the compiler.

Recall that const keeps objects constant, but there may or may not be an object to maintain a constant.

0
Apr 05 '15 at 19:44
source share

Unfortunately, C ++ does not accept it according to design, but logically there are few cases where it validates well.

A function that is a valid class (static) may not change any static data, maybe it will just request data that should be const. Maybe it should be like

 if(Object) MakeThisConstant() else MakeStaticDataConstant() // Only in the scope but static data cannot be constant so may be it should in some scenarios 
0
Jun 11 '16 at 18:32
source share

A "constant member function" is not allowed to modify the object for which it is called, but static member functions are not called for any object. Used directly by the scope resolution operator. Thus, it does not make sense to have a constant static member function, therefore, it is illegal.

0
May 28 '19 at 6:51
source share



All Articles