Is it allowed to write an instance of Derived over an instance of Base?

后端 未结 4 2236
傲寒
傲寒 2020-12-11 22:35

Say, the code

    class Derived: public Base {....}

    Base* b_ptr = new( malloc(sizeof(Derived)) ) Base(1);
    b_ptr->f(2);
    Derived* d_ptr = new(b         


        
4条回答
  •  遥遥无期
    2020-12-11 23:30

    I think the overwrite is allowed.

    If it was me I'd probably call Base::~Base before reusing the storage, so that the lifetime of the original object ended cleanly. But the standard explicitly allows you to reuse the storage without calling the destructor.

    I don't believe your access via b_ptr is valid. The lifetime of the Base object has ended.

    (See 3.8/4 in either standard for the rules on lifetime.)

    And I'm also not entirely convinced that b_ptr must give the same address as was originally returned by the malloc() call.

提交回复
热议问题