2

I'm having the following error while trying to compile the snippet below (using g++):

error: invalid initialization of non-const reference of type
‘std::vector<pos,std::allocator<pos> >&’ from a temporary of
type ‘std::vector<pos, std::allocator<pos> >& 
(*)(std::vector<pos, std::allocator<pos> >&)’

This is the code that generates the error:

struct pos{
  int start;
  int end;
  int distance;
  int size;
};

bool compare_pos(pos a, pos b)
{
  if (a.distance != b.distance)
    return (a.distance < b.distance);
  else
    return (a.size < b.size);
}

vector<pos> sort_matches(vector<pos>& matches)
{
  //vector<pos> sorted_matches(matches);
  vector<pos> sorted_matches();
  //sort(sorted_matches.begin(), sorted_matches.end(), compare_pos);
  return sort_matches;
}

The real code would have the two commented lines uncommented, but even the commented example gives me the error. What am I doing wrong?

Thiago Moraes
  • 617
  • 1
  • 10
  • 22
  • Even with the first line uncommented, you're not posting your real code. Please post an actual, minimal, self-contained example that exhibits your problem. – Kerrek SB May 07 '12 at 12:51
  • @Xeo: The *current* code certainly has the usual vexing parse misunderstanding, but I have a feeling that the original code the OP had in mind was returning a *reference* to a vector. – Kerrek SB May 07 '12 at 12:52
  • Oh, and I just noticed another problem: You're returning `sort_matches`, not `sorted_matches`. That would be the actual problem that also wouldn't allow the commented parts to compile. My bad for the hasty close vote. Voted to reopen. :P – Xeo May 07 '12 at 12:53
  • You are returning the name of the function itself, i.e. a function pointer. That doesn't make sense. – Kerrek SB May 07 '12 at 12:53

1 Answers1

6
vector<pos> sorted_matches();

this declares a function that takes nothing and returns a vector<pos>. This is known as the most vexing parse. If you don't believe me, imagine the variable is named f instead of sorted_matches:

vector<pos> f();

Looks like a function, doesn't it?

Use this to define a default-constructed object:

vector<pos> sorted_matches;
return sorted_matches;
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434