是私人成员黑客定义的行为吗? [英] Is private member hacking defined behaviour?

查看:108
本文介绍了是私人成员黑客定义的行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

class BritneySpears
{
  public:

    int getValue() { return m_value; };

  private:

    int m_value;
};

这是一个外部库(我不能改变)。我显然不能改变 m_value 的值,只读它。即使源自 BritneySpears 也无效。

Which is an external library (that I can't change). I obviously can't change the value of m_value, only read it. Even deriving from BritneySpears won't work.

如果我定义下面的类,该怎么办:

What if I define the following class:

class AshtonKutcher
{
  public:

    int getValue() { return m_value; };

  public:

    int m_value;
};

然后执行:

BritneySpears b;

// Here comes the ugly hack
AshtonKutcher* a = reinterpret_cast<AshtonKutcher*>(&b);
a->m_value = 17;

// Print out the value
std::cout << b.getValue() << std::endl;

我知道这是但只是出于好奇:这是保证工作吗?是否已定义行为?

I know this is bad practice. But just out of curiosity: is this guaranteed to work? Is it defined behaviour?

奖金问题:你曾经使用过这种丑陋的黑客吗?

Bonus question: Have you ever had to use such an ugly hack?

推荐答案

这是未定义的行为。每个访问限定符部分中的成员都保证按照它们出现的顺序进行布局,但是在接受限定符之间没有这样的保证。例如,如果编译器选择将所有私有成员置于所有公共成员之前,上述两个类将有不同的布局。

This is undefined behaviour. The members within each access-qualifier section are guaranteed to be laid out in the order they appear, but there is no such guarantee between acccess qualifiers. For instance, if the compiler chooses to place all private members before all public members, the above two classes will have a different layout.

编辑:回顾这个老的答案,我意识到我错过了一个很明显的点:结构定义每个都有一个数据成员。成员函数的顺序是不相关的,因为它们不会对类的布局有贡献。你可能会发现这两个数据成员都保证在同一个地方,虽然我不知道这个标准是否足够肯定。

Revisiting this old answer, I realized that I missed a rather obvious point: the struct definitions have exactly one data member each. The order of member functions is irrelevant, since they don't contribute to the class's layout. You might well find that both data members are guaranteed to be in the same place, though I don't know the standard well enough to say for sure.

但是!您不能取消引用 reinterpret_cast 在不相关类型之间的结果。它仍然是UB。至少,这是我对 http://en.cppreference.com/w/cpp/的阅读language / reinterpret_cast ,这是一个粗糙的读。

But! You cannot dereference the result of reinterpret_casting between unrelated types. It's still UB. At least, that's my reading of http://en.cppreference.com/w/cpp/language/reinterpret_cast, which is a gnarly read indeed.

这篇关于是私人成员黑客定义的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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