First of all, we know~
class Test { public: Test() { Return this; // the address of the current object returned } Test&() { Return * this; // returns the current object itself } Test() { Return * this; // returns the clone of the current object } private: //... };
Return * this returns the clone or itself of the current object (if the return type is a, it is a copy; if the return type is a &, it is itself).
Return this returns the address of the current object (a pointer to the current object)
Let’s go back to the address where we copied it~
#include <iostream> using namespace std; class Test { public: int x; Test get() { Return * this; // returns the copy of the current object } }; int main() { Test a; a.x = 4; if(a.x == a.get().x) { cout << a.x << endl; cout << &a << endl; cout << &a.get() <<endl; } else { cout << "no" << endl; cout << &a << endl; cout << &a.get() <<endl; } return 0; }
The following error will be reported by the operation result!!!
cpp [Error] taking address of temporary [-fpermissive]
This is because the alert raised by referencing the address of the temporary object is unreliable
All attention!
Let’s talk about the understanding of [C + +] class member return statement return * this
The return statement return * this is often seen in the member functions like copy assignment, and the return type of such functions is usually the reference of the class to which they belong.
The implicit pointer class * this const of a class member function becomes the object itself after it is dereferenced by * this. In this case, if the return type of the member function is class, the returned object will be a copy of the object entity pointed to by this;
If the return type is class &, a reference bound to the object entity pointed to by this will be returned.
summary
The above is the difference between return * this and return this in C / C + + that Xiaobian introduced to you. I hope it will help you. If you have any questions, please leave a message to me, and Xiaobian will reply you in time. Thank you very much for your support of the developepaer website! If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!