如果"this"不是常量,为什么我不能修改它?
If `this` is not const, why can't I modify it?
In this
指针 [class。, c++标准规定:
的成员函数中this
的类型一个类X
是X*
。
。this
不是const
。但是为什么
struct M {
M() { this = new M; }
};
为
error: invalid lvalue in assignment <-- gcc
'=' : left operand must be l-value <-- VC++
'=' : left operand must be l-value <-- clang++
'=' : left operand must be l-value <-- ICC
(source: some online compiler frontends)
换句话说,this
不是const
,但它确实是!
因为在同一段中,还提到this
是prvalue
("纯右值")。
纯右值标准中提到的例子是调用不返回引用的函数的结果,或者像1
、true
或3.5f
这样的字面量。this
-指针不是一个变量,它更像是一个展开为调用函数的对象 ([class.this])的地址的字面值。例如,文字true
的类型是bool
, 不是 bool const
, this
的类型是X*
, 不是 X*const
。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么我的for循环不能正确获取argv
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 为什么我不能在 FOR LOOP 中使用 i/10,C++?
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 为什么模板类中的对象不能返回值
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 变量只能全局"declared",但不能修改/(单独初始化)
- 为什么我不能修改通过引用传递的向量?
- 既然静态成员函数不能修改非静态成员变量,为什么还要使用它呢?
- 为什么函数"strlen"不能像这样修改"ch1"的长度?
- 如果"this"不是常量,为什么我不能修改它?
- 可移植方式(linux 和 Windows)让文件只能由 1 个进程修改,而不能由 C/C++ 中的其他进程修改
- c++中不能修改左值
- 不能修改零?
- 如果我们不能修改set元素,为什么std::set会提供begin()和end()
- 如果没有在互斥对象下修改共享原子变量,则不能正确发布