+ 2
placement new with class destructor
Refer code below: https://code.sololearn.com/cOfJnWCny9kp Question is 1. How to ensure that class destructor is called even with placement new is used. If I am calling delete inside for loop, it obviously crashes. 2. Is placement new is not possible if class constructor allocates memory on heap? 3. Is placement new not possible with smart pointer? 4. What if i ask for more memory via placement new than already allocated in chunk? In other word, what if I am trying to create 10 objects from placement new even if I had only 5 memory space allocated in advance Thanks in advance for your help.
5 odpowiedzi
+ 2
1) you can call the destructor directly:
p->~clsTest();
2) it will work perfectly fine
3) it is possible, it's just not a trivial task
4) it will try to write to a memory location you do not own, so it's behavior is undefined
+ 2
Ketan Lalcheta yes, the constructor will allocate new memory on the heap
Placement new is very useful when you want (or have) to "re-construct" an object
(let's say you want to copy obj1 in obj2, but there is no copy-assignment operator; you can placement new obj2 calling the copy-constructor on obj1)
0
Thanks Angelo
Question on point 2 i.e. constructor allocating memory on heap is possible...
Does this mean new allocation will happen again or mechanism is such that it will not allocate and automatically manage from what we have ? Confused on this actually
0
Yeah . Updated code and it is working for destructor call.
However, what is benefit of placement new if again allocation is done from class constructor? I now tried and constructor calls new memory from heap
0
Thanks Angelo for your help and time , but could not get you.
I updated code to provide copy constructor having deep copy and has not added assignment operator. Also , below code is added in main function:
clsTest* One = new clsTest;
clsTest* Two = One;
delete One;
cout << *(Two->pa) << endl;
I was expecting 9 as output as One is setting value 9 to *pa in constructor.
Is this what you want to say or I missed something?