return object or address

Hi all,

I have this kind of class:

1
2
3
4
5
6
7
class A
{
public:
typedef std::list<std::string> MyList;
private:
MyList list1;
};


And I want to implement a function which will return list1 for me to use it.
When I implement it like this

1
2
3
4
A::MyList getList()
{
return list1;
}


and use it in this function:

1
2
3
4
5
6
7
8
9
10
void f()
{
A a(); //suppose 'a' is constructed properly
A::MyList::const_iterator it = a.getList().begin();
const A::MyList::const_iterator itEnd = a.getList().end();
while( it != itEnd )
{
++it; //Oops!!! I get a segmentation fault on this line.
} 
}


So I get a segmentation fault.
But when I return the address of the list, the program works properly.

Someone explain me please, why is it so?

Thank you very much!!!!!!!
Last edited on
Each call to a.getList() returns a different list. (Another copy of the list).

Write it this way, and you should be ok:
1
2
3
4
5
6
7
8
9
10
11
12
13
void f()
{
     A a(); //suppose 'a' is constructed properly
     A::MyList lst = a.getList() ;

     A::MyList::const_iterator it = lst.begin();
     const A::MyList::const_iterator itEnd = lst.end();

     while( it != itEnd )
    {
          ++it; // ok
    } 
}
Ohhhh yes, right!!!!
I knew that a.getList() will return a copy of my list, but didn't pay attention that I got begin() and end() of different lists. Now I understand the reason of segmentation fault.
Thank you so much!!!!!!!
Last edited on
Topic archived. No new replies allowed.