C++ this pointer, hidden argument in function call

2019-02-20 20:46发布

问题:

I have a stack class with members and a function called push.

class STACK
{
    int data;
    public:
    void push(int x)
    {
        data=x;
    }
}

What does C++ do to convert this statement:

s1.push(3);

to

s1.push(this,3);

Basically my question is what happens under the hood to generate the this pointer and pass it as a hidden argument?

I am actually coding in C. My objective is to have a program which is as close to OOP as possible. For this i have function pointers as members of the structure. Therefore, I want to know if it is possible to somehow have track of which structure called the function (like a "this" pointer ). I don't want to do something like: s1.push(&s1,3); because it beats my purpose.

IS IT possible to convert s1.push(3); to s1.push(&1,3); via MACRO substitution

回答1:

First things first! The statement:

s1.push(3);

is NOT translated to:

 s1.push(this, 3);

But to something like this:

STACK::push(&s1, 3); 

Where STACK::push may be treated as global/namespace or static function under class/namespace STACK, whose prototype would be:

push(STACK const* pThis, int arg);

The this pointer is always the first argument to the method (function). If method has zero argument, it will still have one argument (the this pointer of class).



回答2:

There is no magic

s1.push(3);

is just syntax for

STACK::push(&s1, 3);


回答3:

this = &s1

The address of s1 is known, so it can be passed to STACK::push. It's that simple :)



回答4:

C++ does not exactly convert statements (because C++ is a language specification, and you could implement that language in many ways, even -unethically- with a population of slaves working on paper; you don't need a computer, even if you want one, to have C++). The compiler (e.g. GCC) translates the statement to some other lower level representations. With GCC, it is Gimple statements, and the Gimple representation can be examined, e.g. with MELT's probe or -fdump-tree-gimple and other options (like -fdump-tree-all or -fdump-tree-ssa etc...)



回答5:

Unfortunately, you have to specify the pointer explicitly or implicitly in C.

For C++, it is the compiler's responsibility to set the implicit this pointer as the argument for a class member function. In your code, the member function is mangled as void STACK::push(STACK*, int) in compilation automatically by the compiler, then, when the member function STACK::push is called, the compiler will set the object address (this) as an argument (generally the 1st one) to the member function STACK::push.

No C compiler will offer above functions, thus, it's the users responsibility to set the pointer.



回答6:

After your edit, the question takes up another problem - OOP in C. That's difficult and type-unsafe, but possible to implement. You can look at GObject library, which provides object system in C. I guess it makes heavy use of macros.



标签: c++ this