memory reusing in c++? using placement new with this pointer inside constructor

73 views Asked by At

i had one of these q asked in my test (the output). i searched a lot but unable to understand why

#include <iostream>
using namespace std;
class building{
  public:
    building()  {
    cout<<"geek building"<<endl;
  }
};
   

class house: public building{
  public: 
  house(){
    cout<<"geek house"<<endl;
  }
  house(string name){
    new (this) house();
    cout<<"geek house: string constructor"<<endl;
  }  
};

int main() 
{
  house h("geek");
  return 0;
}

i am having problem with the following

new (this) house;

From n3337, chapter 3.8 (Object lifetime):

A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undeļ¬ned behavior.

my code is giving the following output:

geek building
geek building
geek house
geek house: string constructor

i have following two Questions:

1)is it even legal to use this pointer with placement new inside a constructor of a live object. i know that there wouldn't be a problem if we used another pointer(of the same size)instead of this pointer with placement new. example

new (p2) house;  //p2 is a pointer to class house (house  *p2)

1)according to the above documentation shouldn't my code give a error as i am reusing the old object again after new(this) house ; but the lifetime of the old object has already ended by reusing the memory

can somebody explain why it is not giving an error? and explain the output. any help is appreciated.

0

There are 0 answers