C++11: Private member security [duplicate]

此生再无相见时 提交于 2019-12-22 08:18:20

问题


Let's consider the next code:

#include <iostream>
#include "mydemangled.hpp"

using namespace std;

struct A
{
private:
    struct B {
       int get() const { return 5; }
    };

public:
   B get() const { return B(); }
};

int main()
{
    A a;
    A::B b = a.get();

    cout << demangled(b) << endl;
    cout << b.get() << endl;
}

And the compiler (gcc 4.7.2) yells saying that A::B is private. All right. So, I change the code:

int main()
{
   A a;

   cout << demangled(a.get()) << endl;
   cout << a.get().get() << endl;
}

and it doesn't yell:

$ ./a.out
A::B
5

Meaning, I can't to create instances of A::B, but I can use it. So, new change (the key of my question).

int main()
{
   A a;
   auto b = a.get();

   cout << demangled(b) << endl;
   cout << b.get() << endl;
}

And output:

$ ./a.out
A::B
5

What is the trouble here, being A::B private (and thus its constructors, copy constructors and so on)?


回答1:


In general, access controls names or symbols, not the underlying entities. There are, and always have been, numerous ways of accessing private members; what you cannot do is use the name of such a member.

In your examples, you don't use the name, so there is no problem.



来源:https://stackoverflow.com/questions/15525234/c11-private-member-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!