问题描述
下面的代码正在处理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();
}
我的问题是
- 如果使用
0
进行初始化,则即使下次进行类型转换也不起作用.进行这种类型转换是未定义的行为吗? -
this
指针也是TYPE* const
类型,那么为什么编译器不允许对this
进行相同的操作?
- 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
?
推荐答案
-
正如其他人所说,这是未定义的行为,因为它试图修改
const
对象.如果将其初始化为零,则编译器可能会将其视为编译时常量,而忽略任何对其进行修改的尝试.否则它可能会做一些完全不同的事情.
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"的行为不同?指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!