为什么"TYPE * const"的行为不同?指针? [英] Why different behavior for "TYPE* const" pointers?

查看:100
本文介绍了为什么"TYPE * const"的行为不同?指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码正在处理TYPE* const指针.

Below code is dealing with a TYPE* const pointer.

struct D {
  void Check ()
  {
    D* const p = new D; // 2nd test is "p = 0;"
    cout<<"p = "<<p<<endl;
    (D*&)p = new D;
    cout<<"p = "<<p<<endl; // prints 0, "p = 0;" at declaration
  }
};

int main ()
{
  D o;
  o.Check();
}

我的问题是

  1. 如果使用0进行初始化,则即使下次进行类型转换也不起作用.进行这种类型转换是未定义的行为吗?
  2. this指针也是TYPE* const类型,那么为什么编译器不允许对this进行相同的操作?
  1. If you initialize with 0, then even though typecasting next time will not work. Is doing such typecasting is undefined behavior ?
  2. this pointer is also of TYPE* const type, then why compiler doesn't allow the same operation for this?

推荐答案

  1. 正如其他人所说,这是未定义的行为,因为它试图修改const对象.如果将其初始化为零,则编译器可能会将其视为编译时常量,而忽略任何对其进行修改的尝试.否则它可能会做一些完全不同的事情.

  1. As others have said, this is undefined behaviour since it attempts to modify a const object. If you initialise it with zero then the compiler might treat it as a compile-time constant, and ignore any attempt to modify it. Or it might do something entirely different.

this不是类型为TYPE * const的普通变量;它是类型为TYPE *的右值表达式.这意味着它根本不能用作赋值表达式的目标或绑定到非恒定引用.

this is not an ordinary variable of type TYPE * const; it is an rvalue expression of type TYPE *. This means that it cannot be used as the target of an assignment expression, or bound to a non-constant reference, at all.

这篇关于为什么"TYPE * const"的行为不同?指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆