Addressing memory addresses
If you want to display a pointer using iostreams (for example, for logging), then going through void*is the only way to ensure that it operator<<doesn't get overloaded in some crazy way.
#include <iostream>
struct foo {
};
std::ostream& operator<<(std::ostream& out, foo*) {
return out<<"it a trap!";
}
int main() {
foo bar;
foo *ptr = &bar;
std::cout << ptr << std::endl;
std::cout << static_cast<void*>(ptr) << std::endl;
}
Testing iostream status
iostreams overloads operator void*as a status check, so syntax like if (stream)or while (stream)is a short way to check the status of a stream.
-
, void* , , . SFINAE, , , , .
, dynamic_cast<void*> , :
#include <iostream>
struct other {
virtual void func() = 0;
int c;
};
struct foo {
virtual void func() { std::cout << "foo" << std::endl; }
int a;
};
struct bar : foo, other {
virtual void func() { std::cout << "bar" << std::endl; }
int b;
};
namespace {
void f(foo *ptr) {
ptr->func();
std::cout << ptr << std::endl;
std::cout << dynamic_cast<void*>(ptr) << std::endl;
}
void g(other *ptr) {
ptr->func();
std::cout << ptr << std::endl;
std::cout << dynamic_cast<void*>(ptr) << std::endl;
}
}
int main() {
foo a;
bar b;
f(&a);
f(&b);
g(&b);
}
:
foo
0xbfb815f8
0xbfb815f8
bar
0xbfb815e4
0xbfb815e4
bar
0xbfb815ec
0xbfb815e4
.
ยง 15.3.1 :
, void *, const void*, volatile void * const volatile void *.
, void*. ( , , )
Legacy C
"" C void* , , , ++ .