Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

address of this

Tags:

c++

pointers

this

I try to find address of this pointer, but this code is showing a strange error:

#include <iostream>
using namespace std;
class Base
{
    public:
        void test()
        {
            void *address_of_this =&this;
            cout<<address_of_this<<endl;
        }
};

int main()
{   Base k;
    k.test();

    return 0;
}   //error non-lvalue in unary'&'   

Can you explain this error ?
Also point that what is illegal in taking address of this?

like image 768
T.J. Avatar asked Feb 02 '12 15:02

T.J.


People also ask

How do I find the current object of an address?

example_class* address_of_object(void) { } : The return data type of this function is of a type pointer to the class object. The function does not require any parameters. The 'this' pointer used, returns the address of the current object, which is the class object that is used to call this function in main().

How do I print a pointer address?

You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.

How do you print the address of a pointer in C++?

How do I print the address stored in the pointer in C++? int *ptr = &var; printf("%p", ptr); That will print the address stored in ptr will be printed.

Which unique pointer is automatically passed to a member function when it is invoked?

- When a member function is called, it is automatically passed an implicit argument that is a pointer to the invoking object (ie the object on which the function is invoked). This pointer is known as 'this' pointer.


2 Answers

this is a pointer containing the address to the "current object". It is not a variable that is stored somewhere (or could even be changed), it is a special keyword with these properties.

As such, taking its address makes no sense. If you want to know the address of the "current object" you can simply output:

std::cout << this;

or store as

void* a = this;
like image 144
PlasmaHH Avatar answered Sep 21 '22 01:09

PlasmaHH


Quoting the 2003 C++ standard:

5.1 [expr.prim] The keyword this names a pointer to the object for which a nonstatic member function (9.3.2) is invoked. ... The type of the expression is a pointer to the function’s class (9.3.2), ... The expression is an rvalue.

5.3.1 [expr.unary.op] The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified_id.

To put it simply, & requires an lvalue. this is an rvalue, not an lvalue, just as the error message indicates.

like image 33
Robᵩ Avatar answered Sep 22 '22 01:09

Robᵩ