在 this-> 指针上应用 const_cast

sac*_*ket 2 c++ pointers this const-cast

我正在使用一些代码来消除变量的恒定性。

  int *i = new int(202);
  int *j = new int(402);

  int *const iptr = i;    // Constant pointer
  //iptr = j ;           // Not allowed. Constant pointer cannot point to another location.
  (*iptr)++;             // Allowed
  const_cast<int *>(iptr) = j;
  cout<< *iptr           // prints 402
Run Code Online (Sandbox Code Playgroud)

它按预期工作,但是当我尝试删除“this”指针的恒定性时,编译器不允许这样做,即它在 const_cast 语句下方显示波浪线。

class A
{
public:
  A(A * obj)
  {
    const_cast<A *>(this) = obj; 
  }
};
Run Code Online (Sandbox Code Playgroud)

当我将鼠标悬停在早期代码中的“this”和“iptr”上时(我使用的是 VS2014),我可以看到类型是相同的,即<classname> *const

有人可以解释一下幕后发生了什么吗?

干杯,

萨凯特

Mat*_* M. 6

恐怕你不明白这const_cast是为什么。

在 C++ 中,const用于两种情况:

  • 对象const逻辑值无法更改(并且,除了mutable字段之外,其按位值也无法更改)
  • const*或者const&是只读指针或引用

const_cast不是关于更改const对象,而是关于通过只读指针或引用修改非常量对象

请记住,搬起石头砸自己的脚很容易,因为当你得到一个时,const&你如何知道原始对象const是否是?你不。如果你试图改变一个 const独角兽就会出现,或者可能是魔鬼(也称为未定义行为:任何事情都可能发生)。

现在,与 的相关性this很棘手。严格来说,this它是一个右值(意味着它只能按原样出现在 的右侧 ,尽管为了简单=起见,它通常被描述为const简单的,因此在 的构造函数中A this被描述为具有类型A* const。值得庆幸的是,即使在这种近似下const_cast也是一个坏主意,因为原始对象是const


因此,建议是:

  • Junior:不要使用const_cast,reinterpret_cast或 C 风格的转换(因为当它们对前两个之一进行脱糖时,效果并不明显)。
  • 前辈:你的经验还不够。
  • 专家:来吧!您如何声称自己是专家并尝试使用它们?