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.
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.
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);
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.
While using operator<<
works, you could also use <cstdio>
:
#include <cstdio>
...
MY_CLASS* ptr = MY_CLASS::GetSomeInstance();
fprintf(std::stderr, "Pointer address: %p", ptr);