What is purpose of a “this” pointer in C++? [dupli

2020-05-25 07:53发布

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?

17条回答
不美不萌又怎样
2楼-- · 2020-05-25 08:31
  • 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;
};
查看更多
beautiful°
3楼-- · 2020-05-25 08:31
  1. Resolve ambgiguity between member variables/functions and those defined at other scopes
  2. Make explicit to a reader of the code that a member function is being called or a member variable is being referenced.
  3. Trigger IntelliSense in the IDE (though that may just be me).
查看更多
看我几分像从前
4楼-- · 2020-05-25 08:31

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; }

查看更多
再贱就再见
5楼-- · 2020-05-25 08:32

It lets you pass the current object to another function:

class Foo;

void FooHandler(Foo *foo);

class Foo
{
    HandleThis()
    {
       FooHandler(this);
    }  
};
查看更多
Emotional °昔
6楼-- · 2020-05-25 08:37

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; }
};
查看更多
登录 后发表回答