Placement New in C ++

I have few questions about posting new when reading C ++ Primer Plus.

The sample code in the book is as follows:

class JustTesting{
private:
  string words;
  int number;
public:
  JustTesting(const string & s = "Just Testing", int n = 0){
    number = n;
    words = s;
    //some code here
  }

  ~JustingTesting(){}
};


char * buffer = new char[BUF];   //get a block of memory
JustTesting *pc1, *pc2;

pc1 = new (buffer) JustTesting;  //Place object in buffer
pc2 = new JustTesting("Heap1",20); //Place object on heap

//some code

JustTesting *pc3, *pc4;

pc3 = new (buffer) JustTesting("Bad Idea", 6);
pc4 = new JustTesting("Heap2", 10);

//some code

delete pc2;   //free Heap1
delete pc4;   //free Heap2

pc3->~JustTesting():   //Does the order of these two destructor call
pc1->~JustTesting();   // matters?

delete[] buffer;       //free buffer

The author says that we cannot use

delete pc1;

or

delete pc3;

to delete the objects that they point to, since deletion works in conjunction with a new one, but not with the placement of a new one. For example, the pc3 pointer does not receive the address returned by the new one, but delete pc3will result in a runtime error.

Questions: first, will the object pointed to by pc3 rewrite the one pointed by pc1? If not, how can two different objects remain in the same address. If so, why can we still explicitly call the destructor ( pc1->~JustTesting();) to free the memory of the object.

question two: does the order of these two explicit destructors make sense?

: " pc3 , "? , , , ?

!

+4
4

, ...

pc3 = new (buffer) JustTesting("Bad Idea", 6);

undefined (?). JustTesting buffer, ! . ( ).

delete , ( ) operator new. , operator new[], operator delete[].

" " - . , new(buff) Type(...) Type this, buff. , , .

, operator new -RAII- , , ( ), , , undefined.

, ( ? !) - , , , , . , - , , - , , .

. ptr = new X(...) ...

ptr = malloc(sizeof(X));
new(ptr) X(...);

operator delete ...

ptr->~X();
free(ptr);
+5

: -, , pc3, , pc1? "

, .

, (pc1- > ~ JustTesting();), .

, new. . , , , . - , .

: ?

, , , .

: " pc3 , "? - , ?

, new, ( ). , new, - , .

0

-, , pc3, , pc1?

. , buffer. undefined, , , ( , ).

, (pc1- > ~ JustTesting();), .

, pc1 pc3 . , , , .

pc1 pc3 , , :

char *p1 = new char[50];
char *p2 = p1;
delete [] p2;

" pc3 , "? - , ?

, . , pc3 , new - :

pc3 = new // ... other stuff ...

, , new. new , . new .

, delete , , , . delete , new, - undefined - JustTesting a("Object on stack", 30); delete &a;.

, delete pc3 , pc3->~JustTesting(); delete [] buffer;, - delete [] buffer; , . . , , delete , new.

0

: -, , pc3, , pc1?

.

, (pc1- > ~ JustTesting();), .

pc , , , - UB.

: ?

.

: " pc3 , "? , , , ?

, , " pc3 , ". , .

0

Source: https://habr.com/ru/post/1611222/


All Articles