iterator got by applying begin() on getter method doesn't allow to access to first elements of pointed list

StackOverflow https://stackoverflow.com/questions/23311165

  •  10-07-2023
  •  | 
  •  

سؤال

I have a object's pointer *myObject with a getter method:

vector<string> getList();

When I create my iterator to run throught my list variable returned by getList() like this:

vector<string>::const_iterator it = myObject->getList().begin();

and I display it:

cout << *it << endl;

It displays me nothing (certainly an empty string). It's similar for it+1, it+2, it+3, it+4, but from it+5 it displays the right element

Whereas, when I rewrite the code like this:

vector<string> myList = myObject.getList();
vector<string>::const_iterator it = myList.begin();
cout << *it << endl;

Everything works.

Could you help me to understand this problem please?

Thank you.

هل كانت مفيدة؟

المحلول

When you do this:

vector<string>::const_iterator it = myObject->getList().begin();

At the end of the line, the iterator it is invalid, because the vector<string> returned by getList() is a temporary value.

However, when you store the vector<string> in a local variable, with

vector<string> myList = myObject.getList();

Then, the iterator remains valid, as long as myList is not destroyed.

نصائح أخرى

In the frist case the code has undefined behaviour because the temporary object of type std::vector<std::string> returned by function myObject.getList() will be deleted at the end pf executing the statement. So the iterator will be invalid.

Apart from the valid code in the second example you could also write

const vector<string> &myList = myObject.getList();
vector<string>::const_iterator it = myList.begin();
cout << *it << endl;

that is you could use a constant reference to the temporary object.

The problem is that you are returning a copy of vector, it would go out of scope and out of existance, thus be invalid.

What you want to do is return a const reference to your list.

const vector<string>& getList();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top