Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
752 views
in Technique[技术] by (71.8m points)

performance - Does every c++ member function take `this` as an input implicitly?

When we create a member function for a class in c++, it has an implicit extra argument that is a pointer to the calling object -- referred as this.

Is this true for any function, even if it does not use this pointer. For example, given the class

class foo
{
private:
    int bar;
public:
    int get_one()
    {
      return 1;  // Not using `this`
    }
    int get_bar()
    {
        return this->bar;  // Using `this`
    }
}

Would both the functions (get_one and get_bar) take this as an implicit parameter, even though only one of them actually uses it?
It seems like a bit of a waste to do so.

Note: I understand the correct thing to do would be to make get_one() static, and that the answer may be dependent on the implementation, but I'm just curious.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Would both of the functions (get_one and get_bar) take this as an implicit parameter even though only onle get_bar uses it?

Yes (unless the compiler optimizes it away, which still doesn't mean you can call the function without a valid object).

It seems like a bit of a waste to do so

Then why is it a member if it doesn't use any member data? Sometimes, the correct approach is making it a free function in the same namespace.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...