I have a question about the following code:
#include <iostream>
#include <boost/scoped_ptr.hpp>
class Interface
{
};
class A : public Interface
{
public:
A() { std::cout << "A()" << std::endl; }
virtual ~A() { std::cout << "~A()" << std::endl; }
};
Interface* get_a()
{
A* a = new A;
return a;
}
int main()
{
{
std::cout << "1" << std::endl;
boost::scoped_ptr<Interface> x(get_a());
std::cout << "2" << std::endl;
}
std::cout << "3" << std::endl;
}
It creates the following output:
1
A()
2
3
As you can see, it doesn’t call the destructor of A.
The only way I see to get the destructor of A being called, is to add a destructor for the Interface class like this:
virtual ~Interface() { }
But I really want to avoid any Implementation in my Interface class and virtual ~Interface() = 0; doesn’t work (produces some linker errors complaining about a non existing implementation of ~Interface().
So my question is: What do I have to change in order to make the destructor being called, but (if possible) leave the Interface as an Interface (only abstract methods).
You must define a virtual destructor in the base class, otherwise you’ll get no polymorphic behavior.
And more importantly, you get undefined behavior otherwise; §5.3.5/3:
Emphasis mine.
I’d argue the best is this one:
The compiler can easily inline this, unlike a solution where the implementation resides in a source file. (Speaking of which, this solution doesn’t even mandate you have one.) It also leaves the class pure virtual.