Does the retention period of the new resource use the new object?

#include <cstdlib>
struct B {
    virtual void f();
    void mutate();
    virtual ~B();
};
struct D1 : B { void f(); };
struct D2 : B { void f(); };
void B::mutate() {
    new (this) D2; // reuses storage β€” ends the lifetime of *this
    f(); // undefined behavior - WHY????
    ... = this; // OK, this points to valid memory
}

I need to explain why f()invokation has UB? new (this) D2;reuses storage, but also calls the constructor for D2, and also starts the lifetime of a new object. In this case, f()equal to this -> f(). That is, we just call f()the member function D2. Who knows why this is UB?

+4
source share
2 answers

The standard shows this example Β§ 3.8 67 N3690:

struct C {
  int i;
  void f();
  const C& operator=( const C& );
};

const C& C::operator=( const C& other) {
  if ( this != &other ) {
    this->~C(); // lifetime of *this ends
    new (this) C(other); // new object of type C created
    f(); // well-defined
  }
  return *this;
}

C c1;
C c2;
c1 = c2; // well-defined
c1.f(); // well-defined; c1 refers to a new object of type C

Note that this example completes the lifetime of an object before constructing a new object in place (compare with your code that does not call the destructor).

, :

, , , , , , , , , , :

- , - , ( cv-qualifiers)

- const-qualified, , , - , ,

- (1.8) T T (.. ).

"", .

( , ), undefined .

, vtable, , , , vtable , , , sizeof , , .

+1

:

  • . , .

  • . - , . 9.3.1/2 , X, , X, - X, undefined.

  • , , ( B , D2 B).

, . , , , - ( , D1:: f) ( , D2:: f).

, , , (. 9.5/2 perticularly 9.5/4 ).

+1

All Articles