*this vs this in C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2750316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:35:47  来源:igfitidea点击:

*this vs this in C++

c++this

提问by Mark Rushakoff

I understand what thisdoes, but what is the difference between *thisand this?

我明白是什么this意思,但是*this和之间有什么区别this

Yes, I have Googled and read over *thisin my text book, but I just don't get it...

是的,我*this在我的教科书中搜索并阅读了谷歌,但我就是不明白......

回答by Mark Rushakoff

thisis a pointer, and *thisis a dereferenced pointer.

this是一个指针,并且*this是一个解除引用的指针。

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

如果您有一个返回 的函数this,它将是指向当前对象的指针,而返回的函数*this将是当前对象的“克隆”,分配在堆栈上——除非您指定了该方法的返回类型返回一个引用。

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 copyof our local object, the changes don't persist (because it's a different object entirely), but operating on a reference or pointer doespersist the changes.

您可以看到,当我们对本地对象的副本进行操作时,更改不会持久化(因为它完全是不同的对象),但对引用或指针的操作确实会持久化更改。

回答by Marcelo Cantos

thisis a pointer to the instance of the class. *thisis a referenceto the same. They are different in the same way that int* i_ptrand int& i_refare different.

this是指向类实例的指针。*this是对相同的引用。它们以相同的方式不同,int* i_ptr并且int& i_ref不同。

回答by Chris Hafey

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

没有真正的区别,this->foo()是一样的(*this).foo()