0

Error:

invalid initialization of reference of type Assoc<float, std::basic_string<char> >& from expression of type const Assoc<float, std::basic_string<char> >

for this code

Assoc<keyType,valueType>& found = internalStorage.get(find(key));//returns the value of some key

I'm sorry y'all, I know it's not interesting, but I'm perplexed.

Any ideas what the problem is?

Marius Bancila
  • 16,053
  • 9
  • 49
  • 91

1 Answers1

1

It looks like internalStorage.get() returns the object by value, and you're trying to bind a non-const reference to the returned temporary.

The best way to fix this depends on what it is exactly you're trying to do (and on the type of internalStorage):

  • If you don't need to modify found, make the reference const (and see Does a const reference prolong the life of a temporary?).
  • If you do need to modify found (which is a copy of what's stored in internalStorage), simply remove the &.
  • If you need to modify the object stored in internalStorage, you'll likely need to refactor the code.
Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Indeed. Make the reference const and it should work. Visual C++ unfortunately *does* allow this code :) – heinrichj Feb 28 '14 at 07:14