c++ - 使用 reinterpret_cast 访问私有(private)数据

标签 c++ language-lawyer

这似乎可以成功编译和访问私有(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/

相关文章:

c++ - windows下代码块中链接64位sndfile库

c++ - Clang 和 GCC 不同意使用转换运算符直接初始化的合法性

c++ - 模板内本地类成员的名称查找

c++ - C++17 之前的类模板参数推导

c++ - 迭代器的运算符 * 可以按值返回吗?

c++ - 在开关中声明类对象,然后在开关外使用该变量

c++ - 从套接字读取和转换字节 C++ 的最快方法

c++ - opengl - 使用 glOrtho 时相机看不到物体

c++ - 从二值图像中提取轮廓

c++ - clang 5:std::optional 实例化参数类型的 std::is_constructible 特征