作者dryman (dryman)
看板EE_DSnP
标题Re: [问题] 挂在非常奇怪的地方
时间Fri Dec 11 09:28:37 2009
前情提要..
在AdtTest::getPos中,我的程式会在while那一行挂掉
size_t i = 0;
cout << "Constructing li.." << endl;
AdtType<AdtTestObj>::iterator li = _container.begin();
AdtType<AdtTestObj>::iterator lj = _container.end();
while ((li != lj) && (i++ != pos)) {
cout << "Going to ++li..." << endl;
++li;
cout << "++li.." << endl;
}
用gdb追踪,会发现li根本没被指定为begin()的值
p li里面是垃圾..囧
可是用cout大法的话li的值是正确的..
所以後来我就想会不会是copy constructor或是 operator != 的地方出错
我在"要离开"constructor和operator != 的地方都cout
adt> adta -r 5
adt> adtd -r 5
In copy constructor.._pos = 1 data is 394
in ++().. In operator !=783 911
in ++().. In operator !=798 911
in ++().. In operator !=840 911
in ++().. In operator !=911 911
in ++().. In operator !=911 911
Constructing li..
In copy constructor.._pos = 1 data is 394
In copy constructor.._pos = 1 data is 911
In operator !=394 911
In copy constructor.._pos = 1 data is 394
Command terminated
Command terminated
见鬼了...为什麽会去呼叫copy constructor啊!!!
while ((li != lj) && (i++ != pos)) {
cout << "Going to ++li..." << endl;
++li;
cout << "++li.." << endl;
}
没有任何东西会去呼叫copy constructor啊!?
++()和++(int)我都有加cout来看是否被呼叫
看起来还没碰到++li就喷掉了
只是..为什麽会多一个copy consturctor...
到底是哪来的?(抱头)
更新:
我想测试到底是在while的哪里挂掉
所以将while分成两半,一半放到while里用if+break来取代
结果发现很不可思议的事:
while(++i != pos)会挂掉!!
如果把++i给完全去掉的话就没事
也就是说只有while(li!=lj)的话,程式会执行到删除重复的点才挂掉
我将程式改成
AdtType<AdtTestObj>::iterator getPos(size_t pos) {
#ifdef RANDOM_ACCESS
if (pos >= _container.size()) return _container.end();
return (_container.begin() + pos);
#else
size_t i = 0;
cout << "Constructing li.." << endl;
AdtType<AdtTestObj>::iterator li = _container.begin();
AdtType<AdtTestObj>::iterator lj = _container.end();
while ( li != lj){
cout << *li;
if (i++ == pos) break;
cout << "Going to ++li..." << endl;
++li;
cout << "++li.." << endl;
}
return li;
#endif // RANDOM_ACCESS
}
输出的结果则会是:
Constructing li..
In copy constructor.._pos = 1 data is 394
In copy constructor.._pos = 1 data is 911
In operator !=394 911
394In copy constructor.._pos = 1 data is 394
Command terminated
394是cout << *li;的结果
最诡异的就是i明明就不是iterator, pos也不是
却会呼叫copy constructor..
这实在是太邪门了啊..
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.45.169.1
※ 编辑: dryman 来自: 114.45.169.1 (12/11 09:56)
1F:→ dryman:再更新:我多加了一个cout在if(i++==pos) 前面 12/11 10:02
2F:→ dryman:这样的话这行cout还是会印出来,而copy constructor 12/11 10:02
3F:→ dryman:是在这行cout後面被呼叫.. 12/11 10:03
4F:→ dryman:确认挂掉点了..在return li的时候挂的 12/11 10:08
5F:→ keyboardle:为什麽听起来很像是i被当成li了.... 12/11 10:12
6F:推 ric2k1:return li 是会呼叫 copy constructor 给 return 的 object 12/11 11:41
7F:→ dryman:看来是丢到erase的地方爆掉的..真是脑包sigh.. 12/11 12:32
8F:→ dryman:总之,谢谢老师还有各位强者的提示^ ^ 12/11 12:41