简体   繁体   中英

How to write a pointer to std::cerr?

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);

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