简体   繁体   中英

Can't make a copy of the object by dereferencing unique_ptr but have a segfault

Really have been tortured a lot by the unique_ptr thing.

So, I've defined a private member function of class C which is like:

std::vector<T1> C::mem_fun(std::unique_ptr<T2>& a1,
                           std::vector<T1>& a2,
                           std::vector<T3>& a3) {
    std::vector<T1> b1;
    for (struct {std::vector<T1>::iterator it;
                 std::vector<T3>::iterator iu;}
            gi = {a2.begin(), a3.begin()};
            gi.it != a2.end(); ++gi.it, ++gi.iu) {
        T1 b2;
        ...
        if (...)
            b2.ptr = std::move(gi.it->ptr);
        else {
            ...
            std::unique_ptr<T4> ptr(new T4()); // line 1
            *ptr = *(gi.it->ptr); // line 2 -----> which causes a segfault!!!!
            b2.ptr = std::move(ptr); // line 3
        }
        ...
        b1.push_back(std::move(b2));
    }
    return b1;
}

where T1 is like:

typedef struct T1 {
    int t1_a;
    double t1_b;
    std::unique_ptr<T4> ptr;
} T1;

Why would that statement cause a segfault? Anything wrong with *(gi.it->ptr) ? Or what else? I've heard from somewhere that get() might help, but it turns out not...

What I want to do for line 1-3 basically is make a copy of the object pointed by gi.it->ptr and let the ptr member of b2 point to that copy. Not sure if there are any good solutions? Thanks.

Does T4 have a valid copy constructor for your use case? If so:

b2.ptr = new unique_ptr<T4>(new T4(*gi.it->ptr.get()));

Will do what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM