将此指针分配给指针的右值引用 [英] Assigning this pointer to rvalue reference to a pointer

查看:379
本文介绍了将此指针分配给指针的右值引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否应该编译以下示例?

  struct B; 
struct A
{
A(B *&&){}
};

struct B:A
{
B():A(this){}
};

int main(){}

LWS 与clang它编译,但与gcc我得到:


从'B * const'到'B *&'


的参数1的未知转换

如果我添加一个 const 它编译。<​​/ p>

我也想指出MSVC也错了:


无法将参数2从B * const转换为B *&&'


因此看起来我们在两个编译器中有错误。



BUGS FILED



MSVC错误链接



GCC错误链接

解决方案



实现这个为 cv T * const (其中cv是函数的cv-qualifiers,如果有的话, T 是类类型)。 不是 const ,只是内置类型的prvalue表达式(不可修改)。



许多人认为,因为你不能修改 this 它必须 const ,但作为 Johannes Schaub - litb 曾经评论过很久以前,一个更好的解释是这样的:

  //由编译器
#define this(__this + 0)

//其中__this是这个
的真实值

这里很清楚, this (例如, this = nullptr ),但也清除了 const 对于这样的解释是必要的。 (和你的构造函数中的值只是临时的值。)


Should the following sample compile?

struct B;
struct A
{
  A(B*&&){}
};

struct B : A
{
  B() : A(this){}
};

int main(){}

On LWS with clang it compiles, but with gcc I get:

no known conversion for argument 1 from 'B* const' to 'B*&&'

and if I add a const it compiles.

I would like to also point out MSVC gets it wrong too:

cannot convert parameter 2 from 'B *const ' to 'B *&&'

so it looks like we have a bug in two compilers.

BUGS FILED

MSVC bug link

GCC bug link

解决方案

Yes, that should compile.

It is incorrect to implement this as cv T* const (where cv is the cv-qualifiers for the function, if any, and T is the class type). this is not const, merely a prvalue expression of a built-in type (not modifiable).

Many people think that because you can't modify this it must be const, but as Johannes Schaub - litb once commented long ago, a much better explanation is something like this:

// by the compiler
#define this (__this + 0)

// where __this is the "real" value of this

Here it's clear that you can't modify this (say, this = nullptr), but also clear no const is necessary for such an explanation. (And the value you have in your constructor is just the value of the temporary.)

这篇关于将此指针分配给指针的右值引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆