Today I got a problem. I am in the need of a static
member function, const
is not a must but a better. But, I didn't succeed in my efforts. Can anybody say why or how?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
It is unfortunate that C++ doesn't accept it as per design but logically there are few use cases in which it validates well.
A function which is class level valid(static) might not change any static data, may be it will just query data should be const. May be it should be like
I agree with your question, but unfortunately the C++ is designed that way. For example:
As of today, the
const
is considered in context ofthis
. In a way, it's narrow. It can be made broader by applying thisconst
beyondthis
pointer.i.e. the "proposed"
const
, which may also apply tostatic
functions, will restrict thestatic
members from any modification.In the example code, if
foo()
can be madeconst
, then in that function,A::s
cannot be modified. I can't see any language side effects, if this rule is added to standard. On the contrary, it's amusing that why such rule doesn't exist!Without getting into the details, it's because there may or may not be an object modified by the function, so const is ambiguous to the compiler.
Recall that
const
keeps objects constant, but there may or may not be an object here to keep constant.When you apply the
const
qualifier to a nonstatic member function, it affects thethis
pointer. For a const-qualified member function of classC
, thethis
pointer is of typeC const*
, whereas for a member function that is not const-qualified, thethis
pointer is of typeC*
.A static member function does not have a
this
pointer (such a function is not called on a particular instance of a class), so const qualification of a static member function doesn't make any sense.