在 C++ 中声明 class 时使用私有访问说明符在内存级别提供什么保护?

What protection is provided at the memory level by using the private access specifier in declaring a class in C++?

是否可以溢出到私有变量中?

我不知道从哪里开始研究这个问题,所以任何pointers/help都会很棒!

private 变量仅由编译器生成 private。它们不在某种 unreachableprotected 内存区域中。

如果对象结构众所周知,可以通过浏览内存访问它们(有风险,绝对不推荐,但证明完全没有保护。

作为证明(https://ideone.com/RRsOkr):

#include <iostream>
using namespace std;

class A
{
public:
    A()
    {
        publicAttr = 4;
        privateAttr = 3;
    }
    int publicAttr;
private:
    int privateAttr;
};


int main() {
    A a;
    std::cout << "Public attribute value is:" << a.publicAttr << std::endl;

    void* aVoid = (void*) &a; // works, but char* is recommended (see comment)
    aVoid += sizeof( int );
    int privateAttrValue = *((int*) aVoid);
    std::cout << "Private attribute value is:" << privateAttrValue << std::endl;

    return 0;
}

此程序输出两个属性值,即使其中一个不应该被访问!

4
3

内存级别,完全没有保护。

纯粹是为了开发人员在代码上工作,帮助他们避免错误。

这里有一个例子:

#include <iostream>
using namespace std;

class Test
{
public:
    Test() : x(10) {}
    int getTest() { return x; }
private:
    int x;
};

class Change
{
public:
    int x;
};

int main() {
    Test test; // x is 10
    void* vp = &test;
    Change* modify = (Change*)vp;
    modify->x = 15;
    cout << test.getTest(); // prints 15
    return 0;
}

查看实际效果:http://ideone.com/MdDgUB

访问说明符,如 private、public 和 protected 不提供任何级别的内存保护。