I am trying to know the address of this pointer. tried in the following way.
can anybody suggest me the right method?
I am trying to print cout<<&this<<endl;
in a class member function. but compiler generates error C2102: '&' requires l-value.
Asked
Active
Viewed 385 times
0

David G
- 94,763
- 41
- 167
- 253

Jayakrishna
- 1
- 1
-
2http://stackoverflow.com/questions/6067244/type-of-this-pointer and http://stackoverflow.com/questions/7370109/why-dont-rvalues-have-an-address. you can't get the address of this. it's not of an l-value type. – thang Feb 06 '14 at 02:46
-
You wouldn't even want to. `this` is a hidden parameter to each function call. At the end of the function scope `&this` would not be valid anyway. What would you do with it (in a well behaved program)? – Ed S. Feb 06 '14 at 02:48
-
I assume you want `this` not `&this`... remember this is a pointer to the current object, not a reference. `cout << this` will match `ostream& operator<< (void* val);` after the Standard Conversion per 4.10/2. How the "this" pointer itself is supplied to the function is implementation defined, but you can expect it will be put in a specific register. The compiler has no obligation to support `&this` by falling back on using actual stack memory so it has an address (as it does with other parameters). – Tony Delroy Feb 06 '14 at 02:50
3 Answers
2
If I'm not mistaken, std::cout << this
should suffice.
class Foo
{
public:
void foo()
{
std::cout << this << std::endl;
}
};
int main()
{
Foo foo{};
foo.foo();
}
0
If you want to print the address of a pointer, cast it to a long. Usually you'll want to print it in hexadecimal, rather than decimal- easier to read. You probably don't want to print &this- that would be the address where the pointer to the class is held, my guess is you want to print where the class is. That would just be cout << (long) this;

Gabe Sechan
- 90,003
- 9
- 87
- 127
-
That can be overloaded. Casting it as a long ensures it will be treated as a number. Just cout-ing the pointer will probably work, but I've had it bite me in the ass when doing maintenance work before. (which is one of the many reasons I prefer printf, but separate argument). – Gabe Sechan Feb 06 '14 at 02:55
-
Well, casting it to `long` can also bite. What about when `long` is 32 bits and a pointer is 64? – chris Feb 06 '14 at 03:01
-
Show me a system where that happens. I'll worry about it then. Although feel free to cast to long long if you want to be paranoid. – Gabe Sechan Feb 06 '14 at 03:03
0
C++ pointer is an address. It is just different terms meaning the same thing. So you do not need to get address of the 'this' pointer (which basically means "pointer to the pointer" or "address of the address")
std::cout << this;

Sergii Khaperskov
- 451
- 2
- 6