简体   繁体   中英

Why am I getting an error when using &this?

I know that the this pointer is implicitly passed to member functions when they are called. When I try to get the address of this pointer (via &this ), though, I get the compiler error "lvalue required". Why is this?

class st
{    
  int a,b;
public :
  void print()
  {      
    cout << &this; //gives lvalue required... why?

    cout << this; //will print address of object.
  }   
}

this is not an lvalue but an prvalue. From [class.this]:

In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*.

Emphasis mine

& requires an lvalue so you cannot get the address of this .

Because this pointer is a rvalue. this pointer is a constant value, it is passed to the member function like a local variable, so it's value is stored in a memory location that would become invalid when returning from that function.

Presumably you're trying to print out the values in the object. cout doesn't know how to do this, and you have to teach it. cout << *this; might do this if cout knew how to do it, but you can teach it. Here's an example that is more natural c++. (You should also consider a constructor).

    #include <iostream>
    using namespace std;
    class st
    {
        public:
        int a,b;
    };
    std::ostream& operator<<(std::ostream& s, const st& val)
    {
        return s << "a:" << val.a << " b:" << val.b ;
    }
    int main() {
        st foo;
        foo.a = 1;
        foo.b = 2;
        cout << "foo is " << foo << endl;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM