I am just playing with the placement-new operator. below code compiles and runs without any error on gcc version 11.2.But I am getting one warning as,
warning: 'void operator delete(void*, std::size_t)' called on unallocated object 'buf' [-Wfree-nonheap-object]x86-64 gcc 11.2 #1
Please see the code which I tried,
#include<iostream>
class sample
{
public:
sample()
{
std::cout<<"entered constructor"<<std::endl;
}
~sample()
{
std::cout<<"entered destructor"<<std::endl;
}
};
int main()
{
unsigned char buf[4];
sample* k = new(buf) sample;
delete k;
return 0;
}
Output as follows(I am using compiler explorer for the same)
Program returned: 139
Program stdout
entered constructor
entered destructor
Program stderr
free(): invalid pointer
CodePudding user response:
Using delete
on anything other than pointer returned by an allocating new expression results in undefined beheaviour.
Placement-new doesn't allocate anything. You may not delete
a pointer returned by placement new. In order to destroy an object created using placement new, you must call the destructor explicitly, or you can use std::destroy_at
:
sample* k = new(buf) sample;
std::destroy_at(k);
// or
// k->~sample();