iterator / returning reference to local temporary

  • Thread starter Alexander Stippler
  • Start date
A

Alexander Stippler

Hi,

I've got a question concerning iterators and STL. Why does the compiler
warn, that function dummy in the following example returns a reference
to a local temporary? In my understanding, it is not temporary. It's an
entry in a hash_map and therefore not temporary. Where am I wrong? How do I
get the desired functionality?
And by the way: Does anybody know a real in-depth reference and programming
guide for understanding and above all extending the STL by own data types?

#include <hash_map>
#include <pair.h>
#include <iostream>

std::hash_map<int,int> hash;

const std::pair<int,int> &
dummy(int key) {
return *(hash.find(key));
}

int
main()
{
hash[8] = 9;
dummy(8);
return 0;
}


regards,
Alex
 
R

Rob Williscroft

Alexander Stippler wrote in
Hi,

I've got a question concerning iterators and STL. Why does the
compiler warn, that function dummy in the following example returns a
reference to a local temporary? In my understanding, it is not
temporary. It's an entry in a hash_map and therefore not temporary.
Where am I wrong? How do I get the desired functionality?
And by the way: Does anybody know a real in-depth reference and
programming guide for understanding and above all extending the STL by
own data types?

#include <hash_map>
#include <pair.h>
#include <iostream>

std::hash_map<int,int> hash;

const std::pair<int,int> &
dummy(int key) {
return *(hash.find(key));
}

int
main()
{
hash[8] = 9;
dummy(8);
return 0;
}

You may find that std::hash_map<> (which is non-standard BTW)
actually stores a std::pair<int const, int>. If it were otherwise
you could rewrite the key without the map knowing about it.

Try using:

std::hash_map<int,int>::value_type &

as your return type.

HTH

Rob.
 
A

Alexander Stippler

You may find that std::hash_map<> (which is non-standard BTW)
actually stores a std::pair<int const, int>. If it were otherwise
you could rewrite the key without the map knowing about it.

Try using:

std::hash_map<int,int>::value_type &

as your return type.

HTH

Rob.

Thanks, but your solution is non-standard BTW, too. ;-))
Should be
typename std::hash_map<int,int>::value_type &
^^^^^^^^

regards,
Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top