开发者

Does the 'private' access modifier give the compiler more room for optimization?

Does it allow the compiler to in开发者_如何学Pythonline it, knowing that only functions in the same class can access it? Or is it only for the programmer's convenience?


The compiler can (but is not required to) optimize as you suggest, but that's not the point. The point of access modifiers is to catch certain classes (no pun intended) of programming errors at compile time. Private functions are functions that, if someone called them from outside the class, that would be a bug, and you want to know about it as early as possible.

(Any time you ask the question "could the compiler make optimizations based on this information available to it", the answer is "yes, unless there's a specific rule in the standard that says it's not allowed to" (such as the rules for volatile, whose entire purpose is to inhibit optimizations). However, compilers do not necessarily bother optimizing based on any given piece of information. There is, after all, no requirement for compilers to do any optimization in the first place! How clever your compiler is, nowadays, largely depends on how long you are willing to let it run; MSVC's whole-program PGO mode is capable of inlining through virtual method dispatch -- it guesses the most likely target, and falls back to a regular virtual call at runtime if the guess was wrong -- but slows down compiles by at least a factor of two.)


The access specifiers are a part of C++ mechanism to implement OOP principles of Encapsulation and Abstraction and not optimization for compilers.

Some intelligent compiler can possibly implement some optimization through it but it not enforced to do so by the C++ Standard. The purpose of access specifiers is not Optimization but to facilitate language constructs for principles supported by the C++ language.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜