I want to access shared ptr, which is in union, though segmentation fault happens:
struct union_tmp
{
union_tmp()
{}
~union_tmp()
{}
union
{
int a;
std::shared_ptr<std::vector<int>> ptr;
};
};
int main()
{
union_tmp b;
std::shared_ptr<std::vector<int>> tmp(new std::vector<int>);
b.ptr = tmp; //here segmentation fault happens
return 0;
}
What is the reason of an error and how can I avoid it?
You need to initialize the std::shared_ptr
inside the union:
union_tmp()
: ptr{} // <--
{}
Otherwise, ptr
remains uninitialized, and calling its assignment operator triggers undefined behaviour.
I would use std::variant
for safe C++ "unions" (or boost::variant
if std::variant
is not available for you).
E.g. you may try:
std::variant<int, std::shared_ptr<std::vector<int>>> v;
v = std::make_shared<std::vector<int>>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With