简体   繁体   English

类分配上的映射迭代器错误

[英]Map iterator error on class assignment

I have an error in map iterators. 我在地图迭代器中出错。 The problem is the following: 问题如下:

class JacobianCol
{
private:
...
    JacobianColData::iterator _L_begin;
public:
    JacobianColData::iterator L_begin();
...
};

In another module: 在另一个模块中:

JacobianCol LUSolver::col_subtract(const JacobianColData::iterator &alpha, JacobianCol &X, JacobianCol &Y)
{
    JacobianCol result = Y;

    //alternate "result" variable

    return result;
}

Call: 呼叫:

...
J[*it] = col_subtract(friend_element, J[diag_index], J[*it]);
...

And when I assign result of col_subtract to J[*it] I get J[*it].L_begin pointing to a deallocated memory (pointer to a previous J[*it] ). 当我将col_subtract结果分配给J[*it]我得到J[*it].L_begin指向释放的内存(指向先前的J[*it]指针)。

When you do: 当您这样做时:

JacobianCol result = Y;

result._L_begin keep pointing to Y._col_data.begin(). result._L_begin继续指向Y._col_data.begin()。 When the object which Y is a reference to is deleted, result._L_begin keep pointing to that location, which is now invalid. 当删除以Y为参照的对象时,result._L_begin继续指向该位置,该位置现在无效。

JacobianCol has the _col_data member. JacobianCol具有_col_data成员。 ie, the input instance JacobianCol Y has a _col_data instance and _L_Begin of this is initialized with that map's iterator. 也就是说,输入实例JacobianCol Y具有_col_data实例,并且此_L_Begin使用该地图的迭代器进行初始化。 When you return the result, a different _col_data member is created. 返回结果时,将创建另一个_col_data成员。 Now, the _L_Begin iterator is copied from the original Y instance. 现在,从原始Y实例复制_L_Begin迭代器。 That is why you get the observed behavior. 这就是为什么您得到观察到的行为。

To resolve this implement the copy constructor, copy the map and the re-initialize the iterator by explicitly calling _col_data.begin() in the copy constructor 若要解决此问题,请执行复制构造函数,复制映射并通过在复制构造函数中显式调用_col_data.begin()来重新初始化迭代器。

JacobianCol(const JacobianCol& aSrc_in)
{
    _coll_data = aSrc_in._coll_data;
    _L_Begin = _coll_data.begin();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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