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

Discussion in 'C++' started by Alex Vinokur, Feb 6, 2011.

  1. Alex Vinokur

    Alex Vinokur Guest

    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
     
    Alex Vinokur, Feb 6, 2011
    #1
    1. Advertising

  2. Alex Vinokur

    SG Guest

    On 6 Feb., 06:32, Alex Vinokur <> wrote:
    >
    > 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.
     
    SG, Feb 6, 2011
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jon Rea

    std::vector and size_t

    Jon Rea, Nov 10, 2006, in forum: C++
    Replies:
    3
    Views:
    333
    Andrey Tarasevich
    Nov 10, 2006
  2. earthwormgaz

    Namespace Injection and std::size_t

    earthwormgaz, Nov 16, 2006, in forum: C++
    Replies:
    2
    Views:
    364
    Pete Becker
    Nov 16, 2006
  3. Jon Rea
    Replies:
    4
    Views:
    371
    Marcus Kwok
    Jul 5, 2007
  4. ciccio
    Replies:
    4
    Views:
    1,152
    James Kanze
    Apr 15, 2008
  5. Alex Vinokur
    Replies:
    9
    Views:
    820
    James Kanze
    Oct 13, 2008
Loading...

Share This Page