Search code examples
c++shared-ptrunions

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?


Solution

  • 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.