What does 'return *this' mean in C++?

2019-01-22 22:44发布

I'm converting a C++ program to C#, but this part has me confused. What does return *this mean?

template< EDemoCommands msgType, typename PB_OBJECT_TYPE >
class CDemoMessagePB : public IDemoMessage, public PB_OBJECT_TYPE
{
    (...)
    virtual ::google::protobuf::Message& GetProtoMsg()  { return *this; }
}

How would it translate into C#?

6条回答
Animai°情兽
2楼-- · 2019-01-22 23:25

Using a pointer we can directly access the value stored in the variable which it points to. To do this, we simply have to precede the pointer's identifier with an asterisk (*), which acts as dereference operator and that can be literally translated to "value pointed by".

查看更多
戒情不戒烟
3楼-- · 2019-01-22 23:26

this means pointer to the object, so *this is an object. So you are returning an object ie, *this returns a reference to the object.

查看更多
何必那么认真
4楼-- · 2019-01-22 23:26

You are just returning a reference to the object. this is a pointer and you are dereferencing it.

It translates to C# return this; in the case that you are not dealing with a primitive.

查看更多
唯我独甜
5楼-- · 2019-01-22 23:38

In your particular case, you are returning the reference to 'this', since the return type of the function is a reference (&).

Speaking of the size of returned memory, it is the same as

virtual ::google::protobuf::Message* GetProtoMsg()  { return this; }

But the usage at call time differs.

At call time, you will call store the return value of the function by something like:

Message& m = GetProtoMsg();
查看更多
姐就是有狂的资本
6楼-- · 2019-01-22 23:43

Like in C# this is an implicit pointer to the object you are currently using.
In your particular case, as you return a reference & to the object, you must use *this if you want to return the object you are currently working on.
Don't forget that a reference takes the variable itself, or in case of a pointer (this), the object pointed to (*this), but not the pointer (this).

查看更多
你好瞎i
7楼-- · 2019-01-22 23:49

Watch out that if you try to use return *this; on a function whose return type is Type and not Type&, C++ will try to make a copy of the object and then immediately call the destructor, usually not the intended behaviour. So the return type should be a reference as in your example.

查看更多
登录 后发表回答