这似乎可以成功编译和访问私有(private)数据。这是定义明确的行为吗?
#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问题有点相似,但我相信它不能解决我的问题。
最佳答案
不,行为未定义。对于这样的reintepret_cast
为了有意义,这两个对象必须是可相互转换的
[basic.compound]
4 Two objects a and b are pointer-interconvertible if:
- they are the same object, or
- one is a union object and the other is a non-static data member of that object ([class.union]), or
- one is a standard-layout class object and the other is the first non-static data member of that object, or, if the object has no non-static data members, any base class subobject of that object ([class.mem]), or
- there exists an object c such that a and c are pointer-interconvertible, and c and b are pointer-interconvertible.
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 ]
唯一可能适用的项目是关于标准布局类的项目。如果我们查阅该定义,我们会看到
[class.prop]
3 A class S is a standard-layout class if it:
- has no non-static data members of type non-standard-layout class (or array of such types) or reference,
- [...]
有一个直接的问题。对象的任何非静态数据成员本身必须是标准布局。没有保证
std::string
是标准布局类型。所以行为是不确定的。
关于c++ - 使用 reinterpret_cast 访问私有(private)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63112631/