Search code examples
c++placement-newreinterpret-cast

Reinterpret_cast vs placement new


From reading this post, it is clear that placement news in c++ are used to call a class constructor on a pre-allocated memory location.

In the case that the memory is already initialized, is a placement new or a reinterpret_cast more appropriate?

For example, let's say I read a raw stream of bytes representing a framed message from a TCP socket. I put this stream into a framesync and retrieve a buffer of a known size that represents my class, which I'll call Message. I know of two ways to proceed.

  1. Create a constructor that takes a flag telling the class not to initialize. Do a placement new on the buffer passing the "don't initialize" flag.

    Message::Message( bool initialize ) 
    {
        //
        // Initialize if requested
        //
        if( initialize )
        {
            Reset( );
        }
    }
    
    void Message::Reset( void )
    {
       m_member1 = 1;
       m_member2 = 2;
    }
    
    Message* message = new ( buffer ) Message( false );
    
  2. Use a reinterpret_cast

    Message* message = reinterpret_cast< Message* > ( buffer ); 
    

I believe that both of these will produce an identical result. Is one preferred over the other as more correct, more OO, safer, easier to read, or better style?


Solution

  • The only meaningful rule is this:

    If an instance of some type T has already been constructed at address a, then reinterpret_cast<T*>(a) to get a pointer to the object that already exists.

    If an instance of some type T has not yet been constructed at address a, then use placement new to construct an instance of type T at addres a.

    They are completely different operations.

    The question you need to ask is very, very simple: "does the object already exist?" If yes, you can access it (via a cast). If no, then you need to construct it (via placement new)

    The two operations have nothing to do with each others.

    It's not a question of which one you should prefer, because they do different things. You should prefer the one which does what you want.