InterviewGuide
InterviewGuide copied to clipboard
InterviewGuide 勘误
错误/存疑题目
具体内容
中提到:
E.我们只有获得一个对象后,才能通过对象使用this指针。如果我们知道一个对象this指针的位置,可以直接使用吗?
this指针只有在成员函数中才有定义因此,你获得一个对象后,也不能通过对象使用this指针。所以,我们无法知道一个对象的this指针的位置(只有在成员函数里才有this指针的位置)。当然,在成员函数里,你是可以知道this指针的位置的(可以通过&this获得),也可以直接使用它。
而我在实际测试时发现使用&this
后有如下错误:
test.cpp: In member function ‘void A::func()’:
test.cpp:10:25: error: lvalue required as unary ‘&’ operand
10 | A* const now = &this;
| ^~~~
在StackOverFlow上找到解释如下提问:
https://stackoverflow.com/questions/56832986/is-it-possible-to-obtain-the-address-of-the-this-pointer
https://stackoverflow.com/questions/9114930/address-of-this
Quoting the 2003 C++ standard:
5.1 [expr.prim] The keyword
this
names a pointer to the object for which a nonstatic member function (9.3.2) is invoked. ... The type of the expression is a pointer to the function’s class (9.3.2), ... The expression is an rvalue.
this
is not an lvalue.The
&
requires an lvalue. lvalues are those that can appear on on the left-hand side of an assignment (variables, arrays, etc.).Whereas
this
is a rvalue. rvalues can not appear on the left-hand side (addition, subtraction, etc.).
由SO回答可知根据c++标准this应当为右值, 无法通过&
获取地址
由于我也是小白, 不知道如何准确对this
做定义, 但我认为「当然,在成员函数里,你是可以知道this指针的位置的(可以通过&this
获得),也可以直接使用它。」是有问题的。
感谢,原文已做修改,感谢感谢!!
改了?最后那句话不是没变么?