vendredi 29 janvier 2016

How C++ placement new works?

This question is to confirm I understood the concept right and take expert opinion on style of usages and possible optimization.

I am trying to understand "placement new" and following is the program I came up with...

 1  #include <iostream>
 2  #include <new>
 3
 4  class A {
 5    int *_a;
 6    public:
 7      A(int v) {std::cout<<"A c'tor clalled\n";_a= new int(v);}
 8      ~A() {std::cout<<"A d'tor clalled\n"; delete(_a);}
 9      void testFunction() {std::cout<<"I am a test function &_a = "<<_a<<" a = "<<*_a<<"\n";}
10  };
11  int main()
12  {
13    A *obj1 = new A(21);
14    std::cout<<"Object allocated at "<<obj1<<std::endl;
15    obj1->~A();
16    std::cout<<"Object allocated at "<<obj1<<std::endl;
17    obj1->testFunction();
18    A *obj2 = new(obj1) A(22);
19    obj1->testFunction();
20    obj2->testFunction();
21    delete(obj1);// Is it really needed now? Here it will delete both objects.. so this is not the right place.
22    obj1->testFunction();
23    obj2->testFunction();
24    return 0;
25  }

When I run this program I get following o/p

A c'tor clalled
Object allocated at 0x7f83eb404c30
A d'tor clalled
Object allocated at 0x7f83eb404c30
I am a test function &_a = 0x7f83eb404c40 a = 21
A c'tor clalled
I am a test function &_a = 0x7f83eb404c40 a = 22
I am a test function &_a = 0x7f83eb404c40 a = 22
A d'tor clalled
I am a test function &_a = 0x7f83eb404c40 a = 0
I am a test function &_a = 0x7f83eb404c40 a = 0

I have following question...

  • Is it a correct example to demonstrate placement new?
  • member _a is dynamically allocated (with no placement new). So why it is getting same same address for obj1 & obj2. Is it just a coincidence?
  • is D'tor call on line 15 a good practice?

Please also point out of you see any thing which I can improve on or just do not try. Any good reference or reads are also welcome.

Thanks Vikrant

Aucun commentaire:

Enregistrer un commentaire