无法通过取消引用unique_ptr来复制对象,但存在段错误

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

本文关键字:存在 对象 段错误 错误 复制 取消 引用 ptr unique      更新时间:2023-10-16

真的被unique_ptr的事情折磨了很多。

我定义了C类的private成员函数,它是这样的:

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;
}

其中T1如下:

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

为什么这个语句会导致段错误?*(gi.it->ptr)有什么问题吗?或者还有什么?我从某处听说get()可能有帮助,但事实证明没有…

对于第1-3行,我想做的基本上是复制由gi.it->ptr指向的对象,并让b2ptr成员指向该副本。不确定是否有好的解决方案?谢谢。

T4有一个有效的复制构造函数为您的用例?

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

做你想做的事。