[cfe-dev] operator delete[] does not call derived class destructor
Howard Hinnant
hhinnant at apple.com
Sun May 20 12:13:05 PDT 2012
On May 20, 2012, at 2:23 PM, bd satish wrote:
> Thanks Dmitri and Howard. Given this declaration:
>
> Base* ptr = new Derived[3];
>
> is there any other "fool-proof" alternative to ensure that the
> destructor of Derived objects are always called ? Since it works for
> scalar cases, like,
>
> Base* ptr = new Derived;
> delete ptr;
>
> as an end user, I expect the array version also to behave as such. I
> wonder why the standards decided to make this as "undefined" behavior.
I recommend turning on C++11 support (-std=c++11), turning on libc++ (-stdlib=libc++) and then using vector<unique_ptr<Base>>:
#include <iostream>
#include <memory>
#include <vector>
class Base
{
public:
Base() { }
virtual ~Base() {
std::cout << "In destructor " << __func__ << std::endl;
}
};
class Derived: public Base
{
public:
Derived() {}
~Derived() {
std::cout << "In destructor for " << __func__ << std::endl;
}
};
int main()
{
typedef std::unique_ptr<Base> BasePtr;
std::vector<BasePtr> ptr;
ptr.push_back(BasePtr(new Derived));
ptr.push_back(BasePtr(new Derived));
ptr.push_back(BasePtr(new Derived));
}
In destructor for ~Derived
In destructor ~Base
In destructor for ~Derived
In destructor ~Base
In destructor for ~Derived
In destructor ~Base
Howard
More information about the cfe-dev
mailing list