Partially initialized objects


3 comments on “Partially initialized objects
  1. Julian Andres Klode says:

    m_derivedData will point to uninitialized memory in Base::Base(), so using it fails, as can be trivially seen in valgrind.

    There does not seem to be any way to initialize m_derivedData such that it is valid in Base::Base when compiling with g++, at least, not sure why, I’d expect initializing m_data first to work.

  2. Kunshan Wang says:

    There is nothing wrong with this. m_derivedData is a reference, and it is bound to a region of data storage, not a value. Therefore, it doesn’t matter whether that region of data storage is initialised or not.

  3. dentr says:

    Having references/pointers to yourself is dangerous. It means your default copy/move constructor are not working properly, and most people forget to define a custom move/copy constructor to fix this. So this gets discovered the hard way.

    And the solution isn’t trivial: Base can’t define a copy/move-constructor that works, so it must be non-copyable non-movable, and Derived must implement a move and copy-constructor that works around Base’s limitations.