views:

56

answers:

3

Given:

MY_CLASS* ptr = MY_CLASS::GetSomeInstance();

What is the correct way to output ptr to std::cerr, so I can log its value? Note I don't want to write the class, just the address.

+7  A: 

operator<< is overloaded to take a const void*, so you can simply insert the pointer into the stream:

std::cerr << ptr;

The exception is that if the pointer is a const char*, it will be interpreted as a pointer to a C string. To print the pointer, you need to cast it explicitly to a const void*:

std::cerr << static_cast<const void*>(ptr); 
James McNellis
Except for the stupid `::std::endl` this is an excellent answer. You should use `'\n'` instead, especially for `::std::cerr`.
Omnifarious
@Omnifarious: I just removed it altogether since it's not important to the answer anyway.
James McNellis
@Omnifarious, what's the beef with endl? Is it the flush?
David Gladfelter
@David - That, and the fact that it's used so often people get the bizarre idea that `'\n'` isn't platform independent and `::std::endl` __has__ to be used. 95% of the time I see `::std::endl` used the flush is totally unnecessary. Flushing is very expensive, and in the case of `::std::cerr` completely superfluous.
Omnifarious
+1  A: 

You can leverage boost format for printf like formatting:

std::cerr << format("%p", ptr) << endl;

%p formats pointer - should be portable between x86 and x64.

Igor Zevaka
How is that better than `cerr << ptr << endl`?
Mike Seymour
It's not. Just another option.
Igor Zevaka
+1  A: 

While using operator<< works, you could also use <cstdio>:

#include <cstdio>
...
MY_CLASS* ptr = MY_CLASS::GetSomeInstance();
fprintf(std::stderr, "Pointer address: %p", ptr);
tjko