reinterpret_cast<std::size_t>(p) and reinterpret_cast<std::size_t&>()

A

Alex Vinokur

Hi,

What is the difference between reinterpret_cast<std::size_t>(p) and reinterpret_cast<std::size_t&>(p)?

char* p = new char[100];
std::size_t s1 = reinterpret_cast<std::size_t>(p);
std::size_t s2 = reinterpret_cast<std::size_t&>(p);

Thanks
 
S

SG

What is the difference between
reinterpret_cast<std::size_t>(p) and
reinterpret_cast<std::size_t&>(p)?

char* p = new char[100];
 std::size_t s1 = reinterpret_cast<std::size_t>(p);
 std::size_t s2 = reinterpret_cast<std::size_t&>(p);

The first one converts the pointer value to an int. The C++ standard
guatantees that as long size_t is big enough to hold a pointer value
the roundtrip char* -> size_t -> char* is lossless. This kind of cast
is about converting *values* from one type to another. It's an rvalue
expression.

The second one is equivalent to *reinterpret_cast<size_t*>(&p) which
violates §3.10/15 because it accesses an objekt of type char* called p
as an lvalue of type size_t and hence invokes undefined behaviour.
This kind of cast is about treating a sequence of bytes (referred to
by some lvalue) as an lvalue of a different type. It's an lvalue
expression.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,998
Messages
2,570,242
Members
46,835
Latest member
lila30

Latest Threads

Top