Assigning this pointer to rvalue reference to a pointer
下面的示例是否应编译?
1 2 3 4 5 6 7 8 9 10 11 12 | struct B; struct A { A(B*&&){} }; struct B : A { B() : A(this){} }; int main(){} |
在包含clang的LWS上编译,但在gcc中我得到:
no known conversion for argument 1 from 'B* const' to 'B*&&'
如果我添加一个
我还想指出MSVC也错了:
cannot convert parameter 2 from 'B *const ' to 'B *&&'
所以看起来我们在两个编译器中有一个bug。
虫子场
MSVC错误链接
GCC错误链接
是的,应该编译。
将
很多人认为,因为你不能修改
1 2 3 4 | // by the compiler #define this (__this + 0) // where __this is the"real" value of this |
这里很明显,你不能修改
我说Clang是对的-代码应该编译。出于某种原因,GCC认为
The type of
this in a member function of a classX isX* . If the member function is declaredconst , the type of this isconst X* , if the member function is declaredvolatile , the type of this isvolatile X* , and if the member function is declaredconst volatile , the type of this isconst volatile X* .
所以在这种情况下,
A reference to type"cv1
T1 " is initialized by an expression of type"cv2T2 " as follows:
[...]
[...] or the reference shall be an rvalue reference.
If the initializer expression
is an xvalue, class prvalue, array prvalue or function lvalue and [...], or
has a class type (i.e., T2 is a class type), [...]
then [...]
Otherwise, a temporary of type"cv1 T1" is created and initialized from the initializer expression using the rules for a non-reference copy-initialization (8.5). The reference is then bound to the temporary. [...]