How is access for private variables implemented in C++ under the hood?

前端 未结 2 1660
失恋的感觉
失恋的感觉 2021-01-11 11:27

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?

2条回答
  •  一个人的身影
    2021-01-11 12:03

    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.

    #include 
    
    class FourChars {
      private:
        char a, b, c, d;
    
      public:
        FourChars(char a_, char b_, char c_, char d_)
          : a(a_), b(b_), c(c_), d(d_)
        {
        }
    };
    
    int main()
    {
        FourChars fc('h', 'a', 'c', 'k');
    
        char const *p = static_cast(static_cast(&fc));
    
        std::cout << p[0] << p[1] << p[2] << p[3] << std::endl;
    }
    

    (The complicated cast is there because void* is the only type that any pointer can be cast to. The void* can then be cast to char* without invoking the strict aliasing rule. It might be possible with a single reinterpret_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 :)

提交回复
热议问题