Assigning this pointer to rvalue reference to a pointer

前端 未结 2 2079
感情败类
感情败类 2020-12-16 16:38

Should the following sample compile?

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

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

int main(){}

On LWS

2条回答
  •  悲&欢浪女
    2020-12-16 16:58

    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.)

提交回复
热议问题