1

I'm learning how to use placement new in C++ and I find an example as below:

int main() 
{ 
    // buffer on stack 
    unsigned char buf[100];
    // using placement new 
    Complex *pe = new (buf) Complex(2.6, 3.9);  
    pe->print(); 
    // No delete : Explicit call to Destructor. 
    pe->~Complex(); 

    return 0; 
}

I can understand what the piece of code is doing but I have a question:

Is it possible to remove pe->~Complex()?

As my understanding, the object pe is located on the buf, so it is the buf who is charge of managing the memory. I mean that calling the destructor of pe is not necessary. Am I right?

If there is a new object in the class Complex, obviously we have to delete it in the destructor. Here my question is: must the new object in Complex be located on the buf? Or it may be located on any memory of the stack (just like the normal new)?

Yves
  • 11,597
  • 17
  • 83
  • 180
  • 1
    But `buf` is just an array of bytes... The compiler and least of all the run-time environment doesn't really know the contents of the array. How can a destructor be automatically called then? – Some programmer dude Dec 04 '19 at 07:32
  • 2
    _so it is the `buf` who is charge of managing the memory_ — yes, `buf` "manages" the memory. But _allocation/deallocation_ of memory and _constructing/destructing_ of objects in there are two very different and independent things. BTW, note that `buf` has alignment 1, therefore creating an object of type `Complex` in it might result in misalignment, that is, undefined behavior. – Daniel Langr Dec 04 '19 at 07:37
  • @DanielsaysreinstateMonica What is misalignment? Could you show me some docs or articles about it? – Yves Dec 04 '19 at 07:47
  • @Yves Each type comes with two basic "memory" properties — _size_ and _alignment_. You can find out them with `sizeof` and `alignof` operators. Each object of a given type need to be, in memory, aligned with respect to its type alignment. Alignment for character types, as well as their arrays, is 1. `buf` can be therefore placed at any address in memory, such as 0x0C01. If `alignof(Complex)` is greater then 1, which likely is, then creating an object of type `Complex` in `buf` may lead to misaligned object. For more details, look, e.g., [here](https://en.cppreference.com/w/c/language/object). – Daniel Langr Dec 04 '19 at 07:51

0 Answers0