-1

I'm confused between the subtle differences of passing vectors

This is some part of my program

void print(vector<vector<char>>&field)
vector<vector<char>> bomb(vector<vector<char>>&field)

I encountered a case where I can't do something like this

print((bomb(bomb(field)));

The error is

error: invalid initialization of non-const reference of type 'std::vector<std::vector<char> >&' from an rvalue of type 'std::vector<std::vector<char> >'
             print(bomb(bomb(field)));

But if I add a const to the method definition to

void print(const vector<vector<char>>&field)
vector<vector<char>> bomb(const vector<vector<char>>&field)

Then this will work

What is the difference between

1. vector<vector<char>> bomb(vector<vector<char>>&field)
3. vector<vector<char>> bomb(const vector<vector<char>>&field)
4. vector<vector<char>> bomb(const vector<vector<char>>field)

I believe 1 is passing a vector by reference, which is what I've been doing before. How come I can't do something like bomb(bomb(field)) without the compiler complaining?

user3240815
  • 21
  • 1
  • 5

1 Answers1

2

The return value of bomb is an object, not a reference. The return value is a temporary object. Hence, you cannot use it when the expected type is a non-const reference.

Analogy with simpler objects:

int foo(int& i) { return i+2; }
void bar(int& i) {}

// Can't use
int i = 10;
bar(foo(i));

That is a problem since foo returns a temporary object. Its return value cannot be used as an argument to bar since bar expects a non-const reference.

If the return value of bomb can be changed to a reference,

vector<vector<char>>& bomb(const vector<vector<char>>&field);

without breaking how it works, then you can use:

print((bomb(bomb(field)));
R Sahu
  • 204,454
  • 14
  • 159
  • 270