new, operator new, Placement new, delete
New operator:
C++ supports dynamic allocation of objects using the new operator. This operator allocate memory for object from a pool call free store.The new operator calls the special function operator new.1. We can allocate the memory for any data type.
e.g
int *p = new int;
2. We can also initialize the memory using new operator.
e.g
int *p = new int(50);
3. We can allocate the memory for array using new operator.
e.g
int *p = new int[10];
If enough memory is not available in the free store to allocate, the new request indicates failure by throwing an exception of type std::bad_alloc and new operator returns a pointer.
e.g
#include <iostream>
#include <new>
int main()
{
try {
while (true) {
new int[100000000ul];
}
} catch (const std::bad_alloc& e) {
std::cout << "Allocation failed: " << e.what() << '\n';
}
}
Operator new:
Operator new just allocate enough memory; it doesn't call constructor on that memory.
Placement new:
When we have a raw memory which is already allocated and we need to construct an object in that memory; then "placement new" is used.
deletion:
delete operation perform 2 tasks. first it will call destructor, then it will deallocate memory by calling operator delete.
If we call operator delete then only memory will deallocated no destructor will call.
#include <iostream>
using namespace std;
class XYZ
{
public:
XYZ()
{
cout<<"Constructor"<<endl;
}
~XYZ()
{
cout<<"destuctor"<<endl;
}
};
int main()
{
XYZ *obj = new XYZ;
obj->~XYZ(); //Just call destructor doesnot deallocate memory
return 0;
}
if we allocate memory using new operator then delete should be call to deallocate memory. where as in placement new we create object in specified memory location so delete should not be called for each object.
#include<iostream>
using namespace std;
class myClass
{
int a;
public:
myClass()
{
a = 0;
cout<<"Constructor of myClass"<<endl;
}
};
int main()
{
myClass buff[3];
myClass *ptr1 = (myClass*) new(buff) myclass();
myClass *ptr2 = (myClass*) new(buff+1) myclass;
cout<<"Address of buff is : "<<buff<<endl;
cout<<"Address of ptr1 is : "<<ptr1<<endl;
cout<<"Address of ptr2 is : "<<ptr2<<endl;
return 0;
}
Output:
Constructor of myClass
Constructor of myClass
Constructor of myClass
Constructor of myClass
Constructor of myClass
Address of buff is : 0x7fff9c55d6c0
Address of ptr1 is : 0x7fff9c55d6c0
Address of ptr2 is : 0x7fff9c55d6c4
Comments
Post a Comment