如何在C ++中实现私有变量的访问? [英] How is access for private variables implemented in C++ under the hood?

查看:238
本文介绍了如何在C ++中实现私有变量的访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器如何控制内存中变量的保护?是否有一个标记位与内存中的私有变量相关联?

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?

推荐答案

如果您的意思是 private ,那么在运行时没有任何保护。所有的保护都在编译期发生,如果你知道它们是如何在内存中布局的,你总是可以得到一个类的私有成员。这需要平台和编译器的知识,在某些情况下甚至可能依赖于编译器设置,如优化级别。

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.

例如,在我的Linux / x86-64 w / GCC 4.6,以下程序打印出你所期望的。它绝不是可移植的,并且可能在异乎寻常的编译器上打印出意想不到的东西,但即使这些编译器也会有自己的具体方法来访问私有成员。

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 <iostream>

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<char const *>(static_cast<const void *>(&fc));

    std::cout << p[0] << p[1] << p[2] << p[3] << std::endl;
}

(复杂的转换是因为 void * / code>是任何指针可以转换的唯一类型。 void * 可以转换为 char * ,而不调用严格别名规则。可能使用单个 reinterpret_cast 以及 - 在实践中,我从来没有玩过这种肮脏的技巧,所以我不是太熟悉如何做到最快的方式:)

(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 :)

这篇关于如何在C ++中实现私有变量的访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆