lundi 28 août 2017

No Crash when static member variables are deleted

I have the below code:

#include <iostream>

class A
{
public:

static void* operator new(std::size_t sz) throw();
static void operator delete(void* ptr);
static A obja[2];
static int i;
void show()
{
std::cout << "Called Show" << std::endl;
}
A(const char * where)
{
std::cout << where << std::endl;
}
};

A A::obja[2] = {A("global1"),A("global2")};

int A::i = 0;

static void* A::operator new(std::size_t sz) throw()
{
std::cout << "Called Con " <<  std::endl;
std::cout << "Addr of " << i <<  " " << &obja[i] << std::endl;
return &obja[i++];  
}

static void A::operator delete(void* ptr)
{
i--;
std::cout << "Called Des" << std::endl;
}
int main()
{
(void)A::obja;
A * a1 = new A("local main");
std::cout << "Addr of a1 " << a1 <<  std::endl;
a1->show();
A * a2 = new A("local main");
std::cout << "Addr of a2 " << a1 <<  std::endl;
a1->show();
delete a2;
}

I am purposefully deleting static variable as in code due to some reason - I was expecting that when the program would terminate the global / static variable destruction would happen and an segmentation fault should be observed (cause they are already de-allocated) - but the program terminated successfully:

$ c++ test3.cpp -std=c++11

$ ./a.exe
global1
global2
Called Con
Addr of 0 0x408030
local main
Addr of a1 0x408030
Called Show
Called Con
Addr of 1 0x408031
local main
Addr of a2 0x408030
Called Show
Called Des

Should we not experience a segmentation fault here - is it legitimate?

Aucun commentaire:

Enregistrer un commentaire