With C++26 it is possible to print the address of any pointer.
Advertisement
Rainer Grimm has been working as a software architect, team and training manager for many years. He enjoys writing articles on the programming languages C++, Python, and Haskell, but also frequently speaks at expert conferences. On his blog Modern C++ he discusses his passion C++ in depth.
C++20
bus pointer type void
, const void
And std::nullptr_t
are valid. If you want to display the address of a pointer, you must put it (const) void*
Change.
// formatPointer20.cpp
#include
#include
#include
int main() {
double d = 123.456789;
//std::cout << "&d" << std::format("{}", &d) << '\n';
std::cout << "static_cast(&d): " << std::format("{}", static_cast(&d)) << '\n';
std::cout << "static_cast(&d): " << std::format("{}", static_cast(&d)) << '\n';
std::cout << "nullptr: " << std::format("{}", nullptr) << '\n';
}
In main
the task becomes one double
-variable named d
with value 123,456789
Started. Celebration std::format
Represents the address.
Tries to get the address of the first commented out line d
straight along std::format(„{}“, &d)
to spend. This line is commented out because it will result in a compilation error. Celebration std::format
pointer must be inside void*
Or const void*
Changed to format it correctly.
The next three lines explain how to use pointers. std::format
Formatted and output correctly. The first of these lines contains the address of d
after conversion to void*
Were issued. The address in the second line is d
after conversion to const void*
Were issued. The third row shows the values nullptr
Output, which represents a null pointer.
Here is the output of the program:
When activating a commented out line, a long error message appears.
C++26
With C++26 you can output the pointer directly:
// formatPointer26.cpp
#include
#include
#include
int main() {
double d = 123.456789;
double* p = &d;
std::cout << "&d" << std::format("{:P}", p) << '\n';
}
Frankly, the program can’t be compiled. it contradicts Compiler support for C++26 and offer P2510R3I will reveal why this is so in my next post.
What will happen next?
Concurrency will get two nice features for lock-free data structures with C++26: read-copy updates and hazard pointers.
(rme)