*this vs this in C++

后端 未结 3 1100
逝去的感伤
逝去的感伤 2020-12-12 11:26

I understand what this does, but what is the difference between *this and this?

Yes, I have Googled and read over *this<

相关标签:
3条回答
  • 2020-12-12 11:42

    this is a pointer, and *this is a dereferenced pointer.

    If you had a function that returned this, it would be a pointer to the current object, while a function that returned *this would be a "clone" of the current object, allocated on the stack -- unless you have specified the return type of the method to return a reference.

    A simple program that shows the difference between operating on copies and references:

    #include <iostream>
    
    class Foo
    {
        public:
            Foo()
            {
                this->value = 0;
            }
    
            Foo get_copy()
            {
                return *this;
            }
    
            Foo& get_copy_as_reference()
            {
                return *this;
            }
    
            Foo* get_pointer()
            {
                return this;
            }
    
            void increment()
            {
                this->value++;
            }
    
            void print_value()
            {
                std::cout << this->value << std::endl;
            }
    
        private:
            int value;
    };
    
    int main()
    {
        Foo foo;
        foo.increment();
        foo.print_value();
    
        foo.get_copy().increment();
        foo.print_value();
    
        foo.get_copy_as_reference().increment();
        foo.print_value();
    
        foo.get_pointer()->increment();
        foo.print_value();
    
        return 0;
    }
    

    Output:

    1
    1
    2
    3
    

    You can see that when we operate on a copy of our local object, the changes don't persist (because it's a different object entirely), but operating on a reference or pointer does persist the changes.

    0 讨论(0)
  • 2020-12-12 11:42

    this is a pointer to the instance of the class. *this is a reference to the same. They are different in the same way that int* i_ptr and int& i_ref are different.

    0 讨论(0)
  • 2020-12-12 11:51

    There is no real difference, this->foo() is the same as (*this).foo().

    0 讨论(0)
提交回复
热议问题