What is purpose of this
keyword. Doesn't the methods in a class have access to other peer members in the same class ? What is the need to call a this
to call peer methods inside a class?
问题:
回答1:
Two main uses:
To pass
*this
orthis
as a parameter to other, non-class methods.void do_something_to_a_foo(Foo *foo_instance); void Foo::DoSomething() { do_something_to_a_foo(this); }
- To allow you to remove ambiguities between member variables and function parameters. This is common in constructors.
(Although an initialization list is usually preferable to assignment in this particular example.)MessageBox::MessageBox(const string& message) { this->message = message; }
回答2:
- Helps in disambiguating variables.
- Pass yourself as a parameter or return yourself as a result
Example:
struct A
{
void test(int x)
{
this->x = x; // Disambiguate. Show shadowed variable.
}
A& operator=(A const& copy)
{
x = copy.x;
return *this; // return a reference to self
}
bool operator==(A const& rhs) const
{
return isEqual(*this, rhs); // Pass yourself as parameter.
// Bad example but you can see what I mean.
}
private:
int x;
};
回答3:
Consider the case when a parameter has the same name as a class member:
void setData(int data){
this->data = data;
}
回答4:
- Resolve ambgiguity between member variables/functions and those defined at other scopes
- Make explicit to a reader of the code that a member function is being called or a member variable is being referenced.
- Trigger IntelliSense in the IDE (though that may just be me).
回答5:
The expression *this
is commonly used to return the current object from a member function:
return *this;
The this
pointer is also used to guard against self-reference:
if (&Object != this) {
// do not execute in cases of self-reference
回答6:
It lets you pass the current object to another function:
class Foo;
void FooHandler(Foo *foo);
class Foo
{
HandleThis()
{
FooHandler(this);
}
};
回答7:
Some points to be kept in mind
This pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class.
This pointer is not counted for calculating the size of the object.
This pointers are not accessible for static member functions.
This pointers are not modifiable
Look at the following example to understand how to use the 'this' pointer explained in this C++ Tutorial.
class this_pointer_example // class for explaining C++ tutorial
{
int data1;
public:
//Function using this pointer for C++ Tutorial
int getdata()
{
return this->data1;
}
//Function without using this pointer
void setdata(int newval)
{
data1 = newval;
}
};
Thus, a member function can gain the access of data member by either using this pointer or not. Also read this to understand some other basic things about this pointer
回答8:
It allows you to get around members being shadowed by method arguments or local variables.
回答9:
The this
pointer inside a class is a reference to itself. It's needed for example in this case:
class YourClass
{
private:
int number;
public:
YourClass(int number)
{
this->number = number;
}
}
(while this would have been better done with an initialization list, this serves for demonstration)
In this case you have 2 variables with the same name
- The class private "number"
- And constructor parameter "number"
Using this->number
, you let the compiler know you're assigning to the class-private variable.
回答10:
For example if you write an operator=()
you must check for self assignment.
class C {
public:
const C& operator=(const C& rhs)
{
if(this==&rhs) // <-- check for self assignment before anything
return *this;
// algorithm of assignment here
return *this; // <- return a reference to yourself
}
};
回答11:
The this
pointer is a way to access the current instance of particular object. It can be used for several purposes:
- as instance identity representation (for example in comparison to other instances)
- for data members vs. local variables disambiguation
- to pass the current instance to external objects
- to cast the current instance to different type
回答12:
Sometimes you want to directly have a reference to the current object, in order to pass it along to other methods or to store it for later use.
In addition, method calls always take place against an object. When you call a method within another method in the current object, is is equivalent to writing this->methodName()
You can also use this to access a member rather than a variable or argument name that "hides" it, but it is (IMHO) bad practice to hide a name. For instance:
void C::setX(int x) { this->x = x; }
回答13:
For clarity, or to resolve ambiguity when a local variable or parameter has the same name as a member variable.
回答14:
It also allows you to test for self assignment in assignment operator overloads:
Object & operator=(const Object & rhs) {
if (&rhs != this) {
// do assignment
}
return *this;
}
回答15:
It also allows objects to delete themselves. This is used in smart pointers implementation, COM programming and (I think) XPCOM.
The code looks like this (excerpt from some larger code):
class counted_ptr
{
private:
counted_ptr(const counted_ptr&);
void operator =(const counted_ptr&);
raw_ptr_type _ptr;
volatile unsigned int _refcount;
delete_function _deleter;
public:
counted_ptr(raw_ptr_type const ptr, delete_function deleter)
: _ptr(ptr), _refcount(1), _deleter(deleter) {}
~counted_ptr() { (*_deleter)(_ptr); }
unsigned int addref() { return ++_refcount; }
unsigned int release()
{
unsigned int retval = --_refcount;
if(0 == retval)
>>>>>>>> delete this;
return retval;
}
raw_ptr_type get() { return _ptr; }
};
回答16:
The double colon in c++ is technically known as "Unary Scope resolution operator". Basically it is used when we have the same variable repeated for example inside our "main" function (where our variable will be called local variable) and outside main (where the variable is called a global variable). C++ will alwaysexecute the inner variable ( that is the local one). So imagine you want to use the global variable "Conundrum" instead the local one just because the global one is expressed as a float instead of as an integer:
#include <iostream>
using namespace std;
float Conundrum=.75;
int main()
{
int Conundrum =75;
cout<<::Conundrum;
}
So in this case the program will use our float Conundrum instead of the int Conundrum.
回答17:
One more purpose is to chaining object: Consider the following class:
class Calc{
private:
int m_value;
public:
Calc() { m_value = 0; }
void add(int value) { m_value += value; }
void sub(int value) { m_value -= value; }
void mult(int value) { m_value *= value; }
int getValue() { return m_value; }
};
If you wanted to add 5, subtract 3, and multiply by 4, you’d have to do this: #include int main() { Calc calc; calc.add(5); // returns void calc.sub(3); // returns void calc.mult(4); // returns void
std::cout << calc.getValue() << '\n';
return 0;
}
However, if we make each function return *this, we can chain the calls together. Here is the new version of Calc with “chainable” functions:
class Calc
{
private:
int m_value;
public:
Calc() { m_value = 0; }
Calc& add(int value) { m_value += value; return *this; }
Calc& sub(int value) { m_value -= value; return *this; }
Calc& mult(int value) { m_value *= value; return *this; }
int getValue() { return m_value; }
};
Note that add(), sub() and mult() are now returning *this. Consequently, this allows us to do the following:
#include <iostream>
int main()
{
Calc calc;
calc.add(5).sub(3).mult(4);
std::cout << calc.getValue() << '\n';
return 0;
}
We have effectively condensed three lines into one expression.
Copied from :http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/