为什么“TYPE* const”有不同的行为?指点?
下面的代码处理 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();
}
我的问题是,
- 如果您使用
0
进行初始化,那么即使下次类型转换也将不起作用。做这样的类型转换是未定义的行为吗? 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,
- If you initialize with
0
, then even though typecasting next time will not work. Is doing such typecasting is undefined behavior ? this
pointer is also ofTYPE* const
type, then why compiler doesn't allow the same operation forthis
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如其他人所说,这是未定义的行为,因为它尝试修改
const
对象。如果您将其初始化为零,则编译器可能会将其视为编译时常量,并忽略任何修改它的尝试。或者它可能会做一些完全不同的事情。this
不是TYPE * const
类型的普通变量;它是TYPE *
类型的右值表达式。这意味着它根本不能用作赋值表达式的目标,也不能绑定到非常量引用。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
is not an ordinary variable of typeTYPE * const
; it is an rvalue expression of typeTYPE *
. This means that it cannot be used as the target of an assignment expression, or bound to a non-constant reference, at all.是的。
它会调用未定义的行为,因为它尝试更改 const 指针。
回想一下,
D* const p
声明了一个变量p
,它是一个指向非 constD
的const
指针。Yes.
It invokes undefined behavior, as it tries to change the const pointer.
Recall that
D* const p
declares a variablep
which is aconst
pointer to non-constD
.该声明表明
p
是一个指向常量D
的指针,也就是说它永远不会改变。它始终 0。这里显示 p 的值,您之前说过它始终为 0。猜猜为什么显示 0!
This declaration says that
p
is a pointer toD
that is constant, that is it will never, ever change. It is always 0.Here you display the value of p, which you earlier said would always be 0. Guess why a 0 is displayed!