无法通过取消引用unique_ptr来复制对象,但存在段错误
Can't make a copy of the object by dereferencing unique_ptr but have a segfault
真的被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
指向的对象,并让b2
的ptr
成员指向该副本。不确定是否有好的解决方案?谢谢。
T4有一个有效的复制构造函数为您的用例?
b2.ptr = new unique_ptr<T4>(new T4(*gi.it->ptr.get()));
做你想做的事。
相关文章:
- COM :是否可以查看是否存在对我的某个 COM 对象的进程外引用?我可以释放它吗?
- 堆分配的对象是否存在永不为空的唯一所有者?
- 对象存在与对象生存期不同吗
- 用于从可能不存在的容器中检索对象的 API 设计
- 一个对象的两个指针.删除了一个指针,对象仍然存在
- 放置 新 在共享内存中已存在的对象上
- 是否存在对象存储在其生存期内可能会更改的情况?
- C ++如何创建一个即使对象被覆盖也会持续存在的指针?
- 在另一个对象 B 中创建对象 A 时,对象 A 是否是对象 B 的本地对象,对象 A 是否会存在于对象 B 的实例化之外?
- 指向派生作品的基本指针,即使派生对象不存在
- 调用成员函数,尽管该对象不存在
- GCC:当层次结构中存在虚拟继承时,C++11 内联对象初始化(使用 "this")不起作用
- 为什么当其他类别存在时,为什么不从其对象文件中使用一种类方法
- C++:将数组传递给构造函数并将其保存在 this 对象中
- 不存在的对象的破坏
- 指向可能不存在的对象的指针向量
- C++检查两个地图中是否存在对象
- 检测图像中是否存在对象
- c++ -调用存在对象的构造函数
- 当C++中不存在对象时,如何使其清楚