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

2019-04-25 08:31发布

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?

标签: c++ qt this
3条回答
我想做一个坏孩纸
2楼-- · 2019-04-25 08:39

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.

查看更多
我只想做你的唯一
3楼-- · 2019-04-25 08:42

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

查看更多
贼婆χ
4楼-- · 2019-04-25 08:59

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

查看更多
登录 后发表回答