Re: Missing values in getter
Xavier Pegenaute wrote:
Hi,
I have been developing a code that uses a getter for a map attribute.
But I don't understand the behaviour of the compiled program. Why are
there values missed ?
The code is this:
*****************************************************************************
#include <map>
#include <string>
#include <iostream>
using namespace std;
class Test {
private:
map<string, string> values;
public:
Test();
~Test();
const map<string, string> get_values() const;
Why do you return a const value?
If you return by value, the const-qualification does not give you
anything.
void print();
};
<snip>
int main(){
Test t;
cout<<"-----------First test---------"<<endl;
cout<<"Size: "<<t.get_values().size()<<endl;
map<string, string>::const_iterator it1 =
t.get_values().begin();
Because get_values() returns by value, you get a copy of the map.
Of that copy, you call the begin() member to get an iterator.
But by the time you reach the nest statement, the copy of the map has
been destroyed and your iterator has become invalid.
while(it1 != t.get_values().end()){
Here you start invoking UB, because you use an invalid iterator.
<snip>
Thanks & Regards.
Xavi.
Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://c-faq.com/
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]