开发者

Const method accessing static variables

I apologize if this has been asked before. My search results did not turn up a similar question.

This is a conceptual question. According to MSDN and others as wel开发者_如何转开发l:

A constant member function cannot modify any data members or call any member functions that aren't constant

Why then are we allowed to access static member variables from a const method?


Because they are not part of the object.


The C++ standard says this about const member functions:

If the member function is declared const, the type of this is const X*, [...]

In a const member function, the object for which the function is called is accessed through a const access path; therefore, a const member function shall not modify the object and its non-static data members.

So you see that only non-static data members are part of the 'constness' of the member function.

However, I think that more importantly it indicates that a good way to understand what's going on with const member functions is that it makes the implicit this pointer a pointer to const.

Since static members don't need to be accessed via the this pointer (implicitly or explicitly), access to them isn't const qualified.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜