我正在使用 boost-variant,当在变体中切换类型时,我想确保调用析构函数。以下代码“有效”,但我不知道为什么。我觉得它应该是段错误,因为它正在对未初始化的指针调用删除。幕后是否有一些提升变体的魔法?
#include <iostream>
#include <boost/variant.hpp>
using namespace std;
class A
{
public:
A() {}
virtual ~A() { cout << "Destructing A" << endl; }
};
class B
{
public:
B() {}
virtual ~B() { cout << "Destructing B" << endl; }
};
typedef boost::variant<A*, B*> req;
class delete_visitor : public boost::static_visitor<void>
{
public:
inline void operator() (A *a) const
{
cout << "Will destruct A" << endl;
delete a;
}
inline void operator() (B *b) const
{
cout << "Will destruct B" << endl;
delete b;
}
};
class Wrapper
{
public:
Wrapper(int s) {
setBackend(s);
}
virtual ~Wrapper() {
// cleanup
boost::apply_visitor(delete_visitor(), my_pick);
}
void setBackend(int s)
{
// make sure if we already have put something in our variant, we clean it up
boost::apply_visitor(delete_visitor(), my_pick);
if(s == 0)
my_pick = new A();
else
my_pick = new B();
}
private:
req my_pick;
};
int main()
{
Wrapper *w = new Wrapper(0);
w->setBackend(1);
delete w;
return 0;
}
以下是我得到的输出:
Will destruct A
Will destruct A
Destructing A
Will destruct B
Destructing B