使用reinterpret_cast访问私有数据 [英] Accessing private data with reinterpret_cast
问题描述
这似乎可以成功编译并访问私有数据.这是行为明确的行为吗?
This seems to compile and access the private data successfully. Is this well-defined behavior?
#include <iostream>
#include <string>
using std::string;
class foo {
string private_data = "Hello World";
};
int main()
{
foo f;
auto* pprivate_data = reinterpret_cast<string*>(&f);
std::cout << *pprivate_data << '\n';
}
这个问题有点相似,但我认为它不能解决我的问题.
This question is sort of similar, but I believe it doesn't address my question.
推荐答案
否,该行为未定义.为了使 reintepret_cast
有意义,这两个对象必须是可互换的
No, the behavior is undefined. For such a reintepret_cast
to have meaning, the two objects must be interconvertible
[基本化合物]
4 两个对象a和b是指针可相互转换的如果:
4 Two objects a and b are pointer-interconvertible if:
- 它们是同一个对象,或者
- 一个是联合对象,另一个是该对象的非静态数据成员([class.union]),或者
- 一个是标准布局类对象,另一个是该对象的第一个非静态数据成员,或者,如果该对象没有非静态数据成员,该对象的任何基类子对象([class.mem]),或
- 存在一个对象c,使得a和c是指针可互换的,而c和b是指针可互换的.
如果两个对象是指针可互换的,则它们具有相同的地址,并且有可能从指针获得指向一个的指针通过 reinterpret_cast
互相链接.[注意:数组对象及其第一个元素不是指针可互换的,即使它们具有相同的地址.—尾注]
If two objects are pointer-interconvertible, then they have the same
address, and it is possible to obtain a pointer to one from a pointer
to the other via a reinterpret_cast
. [ Note: An array object and its
first element are not pointer-interconvertible, even though they have
the same address. — end note ]
可能适用的唯一项目符号是关于标准布局类的项目符号.如果我们参考该定义,就会看到
The only bullet that might apply is the one about standard layout classes. If we consult that definition, we see
[class.prop]
3 类S是标准布局类如果它是
3 A class S is a standard-layout class if it:
- 没有非标准布局类(或此类数组)或引用的非静态数据成员,
- [...]
有一个迫在眉睫的问题.对象的任何非静态数据成员本身都必须是标准布局.不能保证 std :: string
是标准布局类型.因此,行为是不确定的.
there is an immediate problem. Any non-static data members of the object must be standard layout themselves. There is no guarantee std::string
is a standard layout type. So the behavior is undefined.
这篇关于使用reinterpret_cast访问私有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!