简体   繁体   中英

How to change the cout format for pointers

I have to write a C++ program on in VS which does the same as a previously written programm for Solaris which is compiled with gcc.

The following "problem" occured:

int var1 = 42;
int* var1Ptr = &var1;
cout << "Address of pointer " << var1Ptr << endl;

This code returns in the solaris program a 0x indexed address (0x08FFAFC).

In my VS code it returns as 008FFAFC.

Since we only do comparison within the code it would be fine, but the supportteam have their own tools which extract data from the logs which is looking for those 0x indexed values. Is there a way to format it like this without adding the 0x prefix everytime we write into the logs?

cout << "Maybe this way: " << hex << int(&var1Ptr) << endl;

doesn't have the effect I wanted.

A little helper class:

namespace detail {

    template<class T>
    struct debug_pointer
    {
        constexpr static std::size_t pointer_digits()
        {
            return sizeof(void*) * 2;
        };
        static constexpr std::size_t width = pointer_digits();

        std::ostream& operator()(std::ostream& os) const
        {
            std::uintptr_t i = reinterpret_cast<std::uintptr_t>(p);
            return os << "0x" << std::hex << std::setw(width) << std::setfill('0') << i;
        }
        T* p;

        friend
        std::ostream& operator<<(std::ostream& os, debug_pointer const& dp) {
            return dp(os);
        }

    };
}

offered via a custom manipulator...

template<class T>
auto debug_pointer(T* p)
{
    return detail::debug_pointer<T>{ p };
}

allows us this expression:

int i;
std::cout << debug_pointer(&i) << std::endl;

Which will yield either an 8-digit or 16-digit hex pointer value, depending on your architecture (mine is 64-bit):

0x00007fff5fbff3bc

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