公共、私人和受保护的幕后 [英] Behind the scenes of public, private and protected

查看:55
本文介绍了公共、私人和受保护的幕后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试更深入地了解公共 | 之间的差异私人 |在 C++ 中从低级角度保护.

I try to dive deeper and understand the differences between Public | Private | Protected in a low level perspective, in C++.

三者的差异在记忆中表现如何?

How are the differences between the three expressed in the memory?

推荐答案

private, publicprotected 不会导致成员被存储在特定的内存区域.访问由编译器检查.在最底层,没有区别.

private, public and protected does not cause members to be stored in specific regions of memory. The access is checked by the compiler. On the very lowest level, there is no difference.

但是,访问说明符确实会影响您对类成员在内存中的排列顺序的保证.

However, access specifiers do have an effect on what guarantees you get on the order in which class members are layed out in memory.

来自 C++17 标准草案:

具有相同访问控制(条款[class.access])的(非联合)类的非静态数据成员被分配,以便后面的成员在类对象中具有更高的地址.具有不同访问控制的非静态数据成员的分配顺序未指定(条款 [class.access]).实现对齐要求可能会导致两个相邻的成员不会立即被分配;管理虚拟函数 ([class.virtual]) 和虚拟基类 ([class.mi]) 的空间需求也是如此.

Nonstatic data members of a (non-union) class with the same access control (Clause [class.access]) are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified (Clause [class.access]). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions ([class.virtual]) and virtual base classes ([class.mi]).

这意味着,对于

 struct foo {
     private:
        int x;
     protected:
        int a;
        int b;
     public:
        int m;
        int n;
     private:
        int y;
};

你只能保证在内存中xy之前,abm 出现在 n 之前.除此之外,未指定成员在内存中的排列顺序.

You only get the guarantee that in memory x comes before y, a comes before b and m comes before n. Other than that, the order in which the members are layed out in memory is unspecified.

然而,内存中成员的顺序很少是有用的信息.因此,说访问说明符与低级内存"无关并不太错.

However, rarely the order of members in memory is a useful information. Hence it isn't too wrong to say that access specifiers have nothing to do with "low level memory".

这篇关于公共、私人和受保护的幕后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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