On Nov 19, 4:09 am, Salt_Peter <pj_h...@yahoo.comwrote:
On Nov 18, 7:17 pm, Prasad <prasadmpa...@gmail.comwrote:
I have been using vector::iterators for a while now. This is
the first time I have encountered this problem.
The vector contains one element.
1. vector<GroupSetTemplate>::iterator gstIt;
2. for(gstIt= this->invariantState.getGroupSetTemplates().begin();
gstIt!=this->invariantState.getGroupSetTemplates().end();gstIt ++)
3{
4 cout<<"Gst name"<<(*gstIt).getName()<<endl;
5}
Line 4 throws me segmentation fault.
However if I rewrite the above code using vector::at() it works fine.
GroupSetTemplate element = invariantState.getGroupSetTemplates().at
(0);
cout<<"Gst name"<<element.getName()<<endl;
So I know that there is no problem with the element. Am I
missing something ?
As already noted, at(0) returns a copy.
No. The function vector<>::at() returns a reference. He makes
the copy afterwards.
Your original code involves iterators. Lets bet member
function getGroupSetTemplates() returns a local variable
(hence the seg fault).
Returns a local variable, or returns a reference to a local
variable. Either could certainly explain his symptoms. (So
could a few other things, but that sounds like a pretty good
guess.)
The fact that you have a conditional expression in that for
loop like so:
gstIt!=this->invariantState.getGroupSetTemplates().end()
is indicative of poor programming practices.
Why? I'd say it was more or less standard practice. In fact, a
for loop without a conditional expression would be an endless
loop. (It's not standard practice to consistently write out the
this->, of course, but maybe this code is in a template, and
invariantState is a member of a dependent base class.)
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34