#include <iostream>
class B {
public:
~B() {
std::cout << "Calling B destructor" << std::endl;
}
};
class A {
public:
A(int refCount):
refCount(refCount)
{}
virtual ~A() {
std::cout << "Calling A destructor" << std::endl;
--refCount;
}
static void operator delete (void *p) {
int refCount = reinterpret_cast<A *>(p)->refCount;
std::cout << "Attempt to delete A, refCount is " << refCount << std::endl;
if (refCount)
return;
std::cout << "Actualy deleting A" << std::endl;
::operator delete(p);
}
private:
int refCount;
B b;
};
int main(int argc, char* argv[]) {
const int refCount = 4;
A * a = new A(refCount);
for (int i = 0; i < refCount; ++i) {
delete a;
}
return 0;
}
Вывод:
Calling A destructor
Calling B destructor
Attempt to delete A, refCount is 3
Calling A destructor
Calling B destructor
Attempt to delete A, refCount is 2
Calling A destructor
Calling B destructor
Attempt to delete A, refCount is 1
Calling A destructor
Calling B destructor
Attempt to delete A, refCount is 0
Actualy deleting A
Содержит ли данный код undefined behaviour?
# clang++-5.0 -std=c++11 -fsanitize=undefined main.cpp
# ./a.out
говорит что всё хорошо.