c++ - 使用公共(public)成员变量的地址来访问私有(private)成员

标签 c++ pointers memory-management

我创建了以下简单的测试程序来表明我可以使用公共(public)整数的地址来访问私有(private)整数的值:

#include <iostream>
using namespace std;
class CarType{
  public:
    int year;
    CarType(int price, int year){this -> year = year; this -> price = price;};
  private: 
    int price;
};

int main(){
  //Create new CarType object
  CarType a = CarType(15000, 1999);
  //Increment the memory address of public member variable, year by 1 and save the result
  int* pricePointer = &a.year+1;
  //De-reference the memory address and output it
  cout << "PRICE: "<< *pricePointer << endl;
  return 0;
}

输出显示我只需知道年份地址就可以访问价格变量。有办法防止这种情况吗?这只是一个边缘情况还是对于所有类型的对象都是如此?

最佳答案

可能是未定义的(但肯定是不明智的)行为,您可以以与防止人们写入随机地址或防止没有经验的人用电锯切断四肢相同的方式来防止它。换句话说,根本不是。

警告编码器。

我在上一段中说可能的原因是它并不完全清楚。在语言律师术语中,请参阅 C++14 5.7 加法运算符/4:

For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

/5 在讨论向指针添加整数值时:

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

在您的情况下,您的指针实际上指向“最后一个元素之后”,因此添加本身不会生成未定义的行为。

您可能认为取消引用对象是未定义的,但根据 3.9.2 复合类型/3 中的注释,它似乎可能是有效的:

For instance, the address one past the end of an array (5.7) would be considered to point to an unrelated object of the array’s element type that might be located at that address.

但是,无论是否未定义,取消引用仍然是不明智的,因为您实际上并不知道那里有一个正确类型的变量。实现可以自由地填充他们认为合适的结构,因此不能保证 price*(year + 1) 相同。

关于c++ - 使用公共(public)成员变量的地址来访问私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37981617/

相关文章:

构造函数的 C++ 语法 "' Object1 a (1, Object1(2) )''

iphone - 为什么在此方法声明中没有*?

c - void** 指针和 void*[] 作为函数参数

ios - ARC 及其工作原理。

c++ - "template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };"是什么意思,它如何与 std::visit 一起使用?

c++ - openssl查询客户端证书

c++ - 带指针的任务

c++ - 为什么 std::allocator::deallocate 需要大小?

python - Python 中的释放内存

c++ - 在 wxWidgets listctrl 中禁用编辑