Shivam Kushwaha
Shivam Kushwaha

Reputation: 1118

Is there any performance cost to always use this pointer in a class

Is there any performance cost to dereference this-> pointer or is it okay to use.

For example:-

Vertex::Vertex(int data)
{
    this->data = data;
    this->visited = false;
}

Upvotes: 2

Views: 619

Answers (2)

Aganju
Aganju

Reputation: 6405

The use of the this-> pointer for dereferencing as shown is optional, and has absolutely no impact on the meaning or the code generated.

There are people who think it's better readable, and people who think it's not, but that's the only difference.

As others recommended, either way, chose a different name for the parameter than the member's name. The compiler will know what you mean, but humans will stumble over the identical names.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234875

There is almost certainly no performance cost, unless you have a particularly bad compiler (or interpreter). The C++ standard does not explicitly say there mustn't be a performance cost, but then again it also refrains from stating the obvious to compiler writers.

this->data &c. are merely syntactic sugar for the member variable of the current object: writing data = data; in the constructor body is essentially a no-op. Better still, write

Vertex::Vertex(int data) : data(data), visited(false)
{
}

where here the compiler is able to disambiguate the variables comprising data(data).

Upvotes: 6

Related Questions