-3

vector<string>& temp = var_obj.funct(); is not working in Linux but except & ITS WORKING FINE. vector<string> temp = var_obj.funct();

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

Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
Raj
  • 1

1 Answers1

0

The problem is that the value returned by the function is temporary. You cannot generate a reference to it because it exists only temporarily. After the function call, the value is gone.

Instead, try this:

vector<string> temp = var_obj.funct();
vector<string> &temp2 = temp;

Now you have a reference with the name temp2.

juhist
  • 4,210
  • 16
  • 33
  • You can generate a reference to it, but it has to be const. – Neil Kirk Mar 26 '15 at 12:01
  • Interesting. I tried to generate a const reference to it, and it works. I didn't know that. Does that reference refer to a valid object? If so, where in memory is that object located? – juhist Mar 26 '15 at 12:05
  • Answering myself: http://stackoverflow.com/questions/2784262/does-a-const-reference-prolong-the-life-of-a-temporary helped. – juhist Mar 26 '15 at 12:07