为什么“TYPE*​​ const”有不同的行为?指点?

发布于 2024-11-01 09:03:07 字数 547 浏览 0 评论 0原文

下面的代码处理 TYPE*​​ const 指针。

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 进行相同的操作呢?

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();
}

My questions are,

  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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

倒带 2024-11-08 09:03:08
  1. 正如其他人所说,这是未定义的行为,因为它尝试修改 const 对象。如果您将其初始化为零,则编译器可能会将其视为编译时常量,并忽略任何修改它的尝试。或者它可能会做一些完全不同的事情。

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

  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.

  2. 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.

请帮我爱他 2024-11-08 09:03:07

进行此类类型转换是未定义的行为吗?

是的。

(D*&)p = new D;

它会调用未定义的行为,因为它尝试更改 const 指针。

回想一下,D* const p 声明了一个变量 p,它是一个指向非 const Dconst 指针。

Is doing such typecasting is undefined behavior ?

Yes.

(D*&)p = new D;

It invokes undefined behavior, as it tries to change the const pointer.

Recall that D* const p declares a variable p which is a const pointer to non-const D.

疧_╮線 2024-11-08 09:03:07
D* const p = 0;

该声明表明 p 是一个指向常量 D 的指针,也就是说它永远不会改变。它始终 0。

cout<<"p = "<<p<<endl;

这里显示 p 的值,您之前说过它始终为 0。猜猜为什么显示 0!

D* const p = 0;

This declaration says that p is a pointer to D that is constant, that is it will never, ever change. It is always 0.

cout<<"p = "<<p<<endl;

Here you display the value of p, which you earlier said would always be 0. Guess why a 0 is displayed!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文