Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
typedef typename set<int>::iterator Iterator;
const Iterator& begin() const {
return s.begin(); //** error
Why I get the following error (I understand the meaning of the error, but, I don't understand why I get it in this case)?
returning reference to temporary [-Werror=return-local-addr]
How can I fix it?
–
–
–
–
The
set<...>::begin
function returns its iterator
by value
. Since you do not store that value anywhere, it's a
temporary
value, and you can't really have references to temporary values.
The simple solution is for your function to
also
return by (non-const) value.
–
–
–
is illegal because the result of
s.begin()
is a temporary object and therefore you can't return a reference to it. Maybe if you look at this equivalent code it will be clearer?
const Iterator& begin() const {
Iterator it = s.begin();
return it; //** error
Returning a const reference to an iterator doesn't make much sense anyway as you wont be able to move the location that the iterator points to. You should always return iterators by value, this way the caller is free to make copies of the iterator and modify their location. For example if you could get your code to compile the following calling code would not work:
Pool p;
const Pool::Iterator& it = p.begin();
++it; //error it is constant
The user could fix their code by copying your returned reference into a new object:
Pool p;
Pool::Iterator it = p.begin();
++it; //no error
As your users wont be able to use the reference you can't return its better just to return by value:
const Iterator begin() const {
return s.begin();
Note that std::set
is not like most other containers and doesn't allow modification of the values via its iterators: https://en.cppreference.com/w/cpp/container/set/begin
Because both iterator and const_iterator are constant iterators (and may in fact be the same type), it is not possible to mutate the elements of the container through an iterator returned by any of these member functions.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.