I don't have access to the Boost library and am trying to implement something similar to Boost any (a container that can store multiple types). I found an example at http://learningcppisfun.blogspot.co.uk/2007/09/boostany.html, however when I compile it I get a segmentation fault. Debugging it seems to suggest that it's Variant's destructor causing an issue. When I comment the destructor out it works fine -- although it's leaking memory. Can anyone explain what's happening? Thanks!
#include <iostream>
#include <vector>
using namespace std;
class BaseHolder
{
public:
virtual ~BaseHolder(){}
};
template<typename T>
class HoldData : public BaseHolder
{
public:
HoldData(const T& t_) : t(t_){}
T t;
};
class Variant
{
public:
template<typename T>
Variant(const T& t) : data(new HoldData<T>(t)){}
~Variant(){delete data;}
BaseHolder* data;
};
int main(){
vector<Variant> a;
int x = 10;
double y = 3.15;
a.push_back(x);
a.push_back(y);
cout << dynamic_cast<HoldData<int> *>(a[0].data)->t << endl;
cout << dynamic_cast<HoldData<double> *>(a[1].data)->t << endl;
return 0;
}
Output:
10
3.5