return a pointer which is "dirty", why constructor function can be called and the program not crash?
1 2 3 4 5 6 7
void *Flower::operatornew(size_t size)
{
cout<<"New function"<<endl;
Flower f;
return &f; //still call new and construct funciton, but I think it should be crash when calling construct function
}
2. When function
void *Flower::operator new(size_t size)
return a NULL pointer, why the constructor function isn't called?
1. You are returning the address of unallocated stack space. The C++ standard does not mandate that a program crash if it accesses unallocated memory. It says the behavior is undefined. In your case, the memory happens
to remain mapped in your process' address space so the construction does not crash, but all the same it writes to memory that is not allocated.
2. The compiler knows better than to call the constructor with a NULL address. C++ allows memory allocation to fail by returning NULL, and it elides the constructor call at that point (as otherwise the behavior is undefined, but on most platforms address 0 is write-protected or unmapped so will result in a program crash) and allows the user to
recover from the failure programmatically.