Access to protected member through member-pointer: is it a hack?

前端 未结 4 958
抹茶落季
抹茶落季 2020-12-07 16:48

We all know members specified protected from a base class can only be accessed from a derived class own instance. This is a feature from the Standard, and this

4条回答
  •  北海茫月
    2020-12-07 17:00

    Basically what you're doing is tricking the compiler, and this is supposed to work. I always see this kind of questions and people some times get bad results and some times it works, depending on how this converts to assembler code.

    I remember seeing a case with a const keyword on a integer, but then with some trickery the guy was able to change the value and successfully circumvented the compiler's awareness. The result was: A wrong value for a simple mathematical operation. The reason is simple: Assembly in x86 does make a distinction between constants and variables, because some instructions do contain constants in their opcode. So, since the compiler believes it's a constant, it'll treat it as a constant and deal with it in an optimized way with the wrong CPU instruction, and baam, you have an error in the resulting number.

    In other words: The compiler will try to enforce all the rules it can enforce, but you can probably eventually trick it, and you may or may not get wrong results based on what you're trying to do, so you better do such things only if you know what you're doing.

    In your case, the pointer &Derived::value can be calculated from an object by how many bytes there are from the beginning of the class. This is basically how the compiler accesses it, so, the compiler:

    1. Doesn't see any problem with permissions, because you're accessing value through derived at compile-time.
    2. Can do it, because you're taking the offset in bytes in an object that has the same structure as derived (well, obviously, the base).

    So, you're not violating any rules. You successfully circumvented the compilation rules. You shouldn't do it, exactly because of the reasons described in the links you attached, as it breaks OOP encapsulation, but, well, if you know what you're doing...

提交回复
热议问题