address of this

2019-03-18 19:06发布

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?

3条回答
做自己的国王
2楼-- · 2019-03-18 19:36

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.

查看更多
混吃等死
3楼-- · 2019-03-18 19:39

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;
查看更多
聊天终结者
4楼-- · 2019-03-18 19:40

this refers to the current object by using it's address.

In your problem, there are two errors:

  • this is not an lvalue.

    The & requires an lvalue. lvalues are those that can appear on on the left-hand side of an assignment (variables, arrays, etc.).

    Whereas this is a rvalue. rvalues can not appear on the left-hand side (addition, subtraction, etc.).

    Reference: C++ Rvalue References Explained.

  • A hidden error which I'd like to also mention is thus:

    address_of_this is actually receiving an address of an address.

    Basically, &this is translated into something like &&object or &(&object).

Basically, think of this as &object (but only to remember because it is not that true).

查看更多
登录 后发表回答