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

I am converting a C ++ program in C #, but this part confuses me. What does return mean * does it mean?

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

How to translate it to C #?

+7
c ++ pointers this
source share
6 answers

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

+13
source share

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

+9
source share

You simply return the link to the object. this is a pointer and you are looking for it.

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

+2
source share

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

Speaking about the size of returned memory, it coincides with

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

But use during the conversation is different.

During the call, you invoke saving the return value of the function with something like:

 Message& m = GetProtoMsg(); 
+2
source share

Using a pointer, we can directly access the value stored in the variable that it points to. To do this, we just need to precede the identifier of the pointer with an asterisk (*), which acts as a dereference operator and can be literally translated to " value specified ".

+1
source share

As in C #, this is an implicit pointer to the object you are currently using.
In your specific case, when you return the & link to an object, you should use *this if you want to return the object you are currently working on.
Do not forget that the variable itself accepts the link or, in the case of the pointer ( this ), the object pointed to ( *this ), but not the pointer ( this ).

+1
source share

All Articles