0

Let's say I have a struct :

struct structazauras
{ 
string bla;
}

And some function (in my case this function is actually a constructor of some class but I don't think this is the issue):

void myfunc(structazauras& mystruct) { }

then some where i call myfunc :

..
myfunc(structazauras());
..

I get an error:

no matching function for call to myfunc(structazauras) candidates are myfunc(structazauras&)

If I change the code to :

structazauras tmp;
myfunc(tmp);

It will work fine.

I feel that he (the compiler) has a problem passing a reference to the anonymous instance if structazauras, but why ? the anonymous instance exist on the stack of the calling function.

OopsUser
  • 4,642
  • 7
  • 46
  • 71

1 Answers1

2

That is because you cannot bind a temporary to a non-const reference. Mark your reference as const and it will work.

Also, you are using a standard C++ keyword (struct) in the definition

void myfunc(structazauras& struct) { }

Change the name to something else. Or maybe you meant

void myfunc(struct structazauras&) { }

but the additional struct is superfluous in C++.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • why i can't bind temporary to non-const reference ? what is the difference between the life expectancy of tmp instance vs the anonymous instance, they both live on the stack, aren't they ? – OopsUser May 11 '15 at 13:18
  • @OopsUser I guess the C++ standard didn't want to keep alive temp objects while allowing you to further modify them. Not absolutely sure that this is the reason, but it makes some sense. – vsoftco May 11 '15 at 13:20
  • @OopsUser: To avoid confusion, for example if a type conversion causes the reference to bind to a temporary, when you expect it to modify an existing variable. See the dupe for full details. – Mike Seymour May 11 '15 at 13:20