开发者

the "this" pointer inside a class

the question is simpl开发者_JAVA百科e... is there any difference in using this->yourvariable or yourvariable directly for some reason?

I am not finding any problem with that, but I am using this-> a lot and would like to know if there is any difference before going further.

I saw a comment on a post here and I don't remember which thread, but the person said something about using the keyword "this".

Personally, I find it nice to use than the variable directly. It makes the code more easier and pretty.

Joe


In most cases there is no difference. But there are situations where it makes a difference:

class foo
{
    int i;
    void bar() {
        int i = 3;
        i; // refers to local i
        this->i; // refers to the member i
    }
};

Also, with templates you may need to qualify a member with this-> so that name lookup is delayed:

template<typename T>
struct A
{
    int i;
    T* p;
};

template<typename T>
struct B : A<T>
{
    void foo() {
        int k = this->i; // here this-> is required
    }
};

A compiler that properly does the "two phase lookup" will complain in case you remove "this->" that it doesn't know what i is supposed to be. "this->" tells it that it's a member from a base class. Since the base class depends on a template parameter, lookup is delayed until the class template is instantiated.


No, there is no real difference, it is simply a scope qualifier. However, suppose a method

void SetFoo( Foo foo )
{
    this->foo = foo;
}

where this->foo is a private member. Here it allows you to take a parameter with the same name as a class/instance variable.


I find that using this makes my code more readable, but there's no reason that you have to. If you look at the assembler code your compiler generates, it should be functionally (and usually literally) identical.

Basically, when the function is called, it is passed a hidden argument this which is then used to figure out which variables are where. If you use the variables directly, without a this->, you're not doing anything except making use of some syntactic sugar.


This was kind of asked and answered about C# here and I think that the answer (at least mine) is the same. It is preference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜