0

What does memory reuse mean? For instance, we've created and object.

struct A { };
A *a = new A;
void *p = operator new(sizeof(A),a); //Is it memory reusing?
void *p = realloc(sizeof(A),a); //Is it memory reusing?

I ask that question because the example from the section 3.8/6 confuses me. The example:

#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; //1, reuses storage — ends the lifetime of *this
    f(); // undefined behavior
    ... = this; // OK, this points to valid memory
}

That is, at //1 we first call placement-new which reuses memory, and just after this we construct a new object. Right?

suspectus
  • 16,548
  • 8
  • 49
  • 57
St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • Why is it Undefined Behaviour? – david.pfx Sep 05 '14 at 06:24
  • @david.pfx: See http://stackoverflow.com/questions/9117358/is-it-allowed-to-write-an-instance-of-derived-over-an-instance-of-base – Ben Voigt Sep 07 '14 at 12:03
  • The placement form of the allocation function is *always* a no-op. (The library version is, and the Standard makes your whole program undefined behavior if you supplant the library version, see section `[new.delete.placement]`) – Ben Voigt Sep 07 '14 at 12:06
  • @BenVoigt: No, I don't think that's it. I think it must be S3.8/5 `the pointer is used to access a non-static data member or call a non-static member function of the object`. – david.pfx Sep 07 '14 at 14:10
  • @david.pfx: My two comments above are completely unrelated to each other. – Ben Voigt Sep 07 '14 at 15:42
  • @david.pfx: The undefined behavior there comes because that rule DOES apply, and 3.8/7 does not. – Ben Voigt Sep 07 '14 at 15:44
  • @BenVoigt (1) Yes, I realised (2) I think we are in furious agreement. – david.pfx Sep 08 '14 at 05:50

2 Answers2

4

Here, storage reuse simply means that the new object is constructed at the address pointed to by this, wherever that might be. In other words, no new memory is allocated for the object.

realloc() is not a memory reuse tool since it can lead to a new block being allocated. Furthermore, your example has undefined behaviour, since you can't use realloc() on memory allocated using new.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

Storage reuse happens when any write to any memory occupied by the object takes place, and that write is not performed via a layout-compatible type (basically strict aliasing, but you'd better not use the exception for character types to overwrite parts of an object that isn't trivially copyable).

Using placement new to construct a new object is one example, but another example is using memcpy to copy another object on top of it.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720