使用大小 8 的未初始化值
我正在实现的 fwd_iterator 遇到了一个非常奇怪的问题:
如果我在类内部定义的方法中使用迭代器,它们就可以工作,但是如果我创建一个具有全局范围的方法,在其中使用迭代器,valgrind 会说我正在尝试访问未初始化的内存。
似乎在类外部创建的迭代器无法读取类的私有属性(即使创建了公共方法来执行此操作)。
这是全局范围的方法:
template<typename T, class Pred>
int evaluate(SparseMatrix<T> &sm, Pred pred){
typename SparseMatrix<T>:: iterator begin, end;
int count=0;
begin=sm.begin();
end=sm.end();
while(begin!=end){
if(pred(*(begin->data))) count++;
begin++;
}
int dcount=0;
if(pred(sm.getDef())) dcount = ((sm.getRows() * sm.getCols()) - sm.getSize());
return count+dcount;
}
这是类内部的方法:
void print_it() {
iterator x=begin();
iterator y=end();
int i=1;
while(x!=y){
cout<<i<<".("<<(x->i)<<","<<(x->j)<<")="<<*(x->data)<<endl;
++x;
i++;
}
if(x==y) cout<<"End."<<endl;
cout<<endl;
}
已解决: 迭代器类有两个属性,value_type val 和 sm(指向类本身的指针)。在operator=(const iterator& other)中我忘记在val=other.val;之后添加sm=其他.sm;线。
现在一切正常了!
I'm having a quite strange problem with the fwd_iterator that I'm implementing:
if I use the iterators in methods defined inside the class, they work, but if I create a method with global scope in which I use iterators, valgrind says that I'm attempting to access to uninitialised memory.
It seems like iterators created outside the class cannot read a private attribute of the class (even with public methods created to do this).
This is the global-scope method:
template<typename T, class Pred>
int evaluate(SparseMatrix<T> &sm, Pred pred){
typename SparseMatrix<T>:: iterator begin, end;
int count=0;
begin=sm.begin();
end=sm.end();
while(begin!=end){
if(pred(*(begin->data))) count++;
begin++;
}
int dcount=0;
if(pred(sm.getDef())) dcount = ((sm.getRows() * sm.getCols()) - sm.getSize());
return count+dcount;
}
This is the inside-class method:
void print_it() {
iterator x=begin();
iterator y=end();
int i=1;
while(x!=y){
cout<<i<<".("<<(x->i)<<","<<(x->j)<<")="<<*(x->data)<<endl;
++x;
i++;
}
if(x==y) cout<<"End."<<endl;
cout<<endl;
}
Solved: iterator class has two attributes, value_type val, and sm, a pointer to the class itself. In operator=(const iterator& other) I forgot to add after val=other.val; the sm=other.sm; line.
Now everything works!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
迭代器类有两个属性,value_type val 和 sm(指向类本身的指针)。在operator=(const iterator& other)中我忘记在val=other.val;之后添加sm=其他.sm;线。
现在一切正常了!
iterator class has two attributes, value_type val, and sm, a pointer to the class itself. In operator=(const iterator& other) I forgot to add after val=other.val; the sm=other.sm; line.
Now everything works!