Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared ptr in union

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?

like image 485
Aleksandr Tukallo Avatar asked Oct 28 '16 09:10

Aleksandr Tukallo


2 Answers

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.

like image 67
Quentin Avatar answered Oct 10 '22 04:10

Quentin


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>>();
like image 38
Mr.C64 Avatar answered Oct 10 '22 04:10

Mr.C64