What does assignment to *this do (*this = val)?

2019-04-25 08:00发布

问题:

I was browsing Qt sources, and noticed this

QUuid &operator=(const GUID &guid)
{
    *this = QUuid(guid);
    return *this;
}

I've never seen assignment to "this" before. What does assignment to "this" do?

回答1:

That is not an assignment to this but to the object pointed by this. That will effectively call operator=( QUuid const & ) on the current object.



回答2:

It just invokes QUuid &operator=(const QUuid& quUid);.



回答3:

'this' is simply a pointer to the object on which the current method is invoked. Changing the value behind 'this' (by dereferencing the pointer using '*this' and assigning another object) modifies the caller's object to become another one.

In your example, a caller of 'operator=' might do the following:

GUID guid = guid(...) ;
QUuid uid = guid ;

According to the definition of 'operator=' this action copy-converts 'guid' into a new object of type 'QUuid'.



标签: c++ qt this