开发者

How to write a pointer to std::cerr?

开发者 https://www.devze.com 2023-01-07 00:33 出处:网络
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 addres

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

精彩评论

暂无评论...
验证码 换一张
取 消