为什么这种类型的擦除实现(简化的 boost:any)会出现分段错误
Why does this type erasure implementation (simplified boost:any) gives segmentation fault?
我正在尝试自己实现任意类型的通用容器(类似于boost:any),只是为了了解这个习语,我试图理解为什么我的代码给出了分段错误。
class IValue
{
public:
IValue() = default;
virtual ~IValue() = default;
};
template<typename T>
class Value : public IValue
{
public:
Value(T value) : val(value){}
virtual ~Value() override
{
}
T get()
{
return val;
}
private:
T val;
};
class any
{
public:
template<typename U>
any(U element)
{
elem = new Value<U>(element);
}
~any()
{
delete elem;
}
IValue* get_type_erased_value()
{
return elem;
}
private:
IValue* elem;
};
template<typename T>
T any_cast(any a)
{
Value<T>* stored_element = dynamic_cast<Value<T>*>(a.get_type_erased_value());
if(stored_element)
{
return stored_element->get();
}
else
{
cout << "Any cast failed. Could not cast down to required typen";
return T();
}
}
struct foo
{
int a;
float b;
char c;
};
ostream& operator<<(ostream& stream, foo& a)
{
stream << '{' << a.a << ',' << a.b << ',' << a.c << '}' << 'n';
return stream;
}
int main()
{
any a = string("Any string value");
any b = int(17);
any c = foo({27,3.5,'g'});
string s = any_cast<string>(a);
int i = any_cast<int>(b);
foo f = any_cast<foo>(c);
cout << "Any string contained: " << s << 'n';
cout << "Any int contained: " << i << 'n';
cout << "Any struct foo contained: " << f << 'n';
return 0;
}
输出是我想要的,转换似乎工作正常,但程序总是在最后崩溃。析构函数未正确调用或指针的释放一定有问题。有人可以给我一个提示吗?
谢谢
any
类型的隐式定义复制构造函数仅复制IValue
指针,因此原始对象和副本都将删除相同的指针。您需要编写一个实际复制存储对象的复制构造函数。
相关文章:
- 分段故障(堆芯转储)矢量
- 数组的指针从不分段故障
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 在线编译器中的分段C++没有打印消息
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 哪些类型可以转换为std::any
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么这种类型的擦除实现(简化的 boost:any)会出现分段错误