How does the compiler control protection of variables in memory? Is there a tag bit associated with private variables inside the memory? How does it work?
相关问题
- 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's the compiler's job to see that some members are private and disallow you from using them. They aren't
anymuch different from other members after compilation.There is however an important aspect, in that data members aren't required to be laid out in memory in the order in which they appear in the class definition, but they are required to for variables with the same access level.
If you mean
private
members of instances, then there's no protection whatsoever at run-time. All protection takes place at compile-time and you can always get at the private members of a class if you know how they are laid out in memory. That requires knowledge of the platform and the compiler, and in some cases may even depend on compiler settings such as the optimization level.E.g., on my Linux/x86-64 w/GCC 4.6, the following program prints exactly what you expect. It is by no means portable and might print unexpected things on exotic compilers, but even those compilers will have their own specific ways to get to the private members.
(The complicated cast is there because
void*
is the only type that any pointer can be cast to. Thevoid*
can then be cast tochar*
without invoking the strict aliasing rule. It might be possible with a singlereinterpret_cast
as well -- in practice, I never play this kind of dirty tricks, so I'm not too familiar with how to do them in the quickest way :)