Common member in the compound

I want to access the shared ptr, which is in the union, although a segmentation error occurs:

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 cause of the error and how to avoid it?

+4
source share
2 answers

You need to initialize std::shared_ptrinside the union:

union_tmp()
: ptr{} // <--
{}

Otherwise, it ptrremains uninitialized, and a call to its assignment operator causes undefined behavior.

+4
source

I would use std::variantC ++ for secure "unions" (or boost::variant, if std::variantnot available to you).

eg. you can try:

std::variant<int, std::shared_ptr<std::vector<int>>> v;
v = std::make_shared<std::vector<int>>();
+6
source

Source: https://habr.com/ru/post/1659168/


All Articles