-9

push_backing to a vector with function updated values doesn't permit why?

std::vector< std::string >goin;
goin.push_back(function(somestringvalue)); // why cant it take update value?

void function(std::string& var)
{
    var += "pre";
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
rosti
  • 1
  • 4

1 Answers1

5

As others have said, the problem is that function doesn't return anything. The way to fix this is to have it return its argument:

const std::string& function(std::string& var) {
    var += "pre";
    return var;
}

This way it modifies the string that's passed to it, and it returns a reference to that string so that you can push it into the vector.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • 2
    Is there a reason to return a `const std::string&` instead of a `std::string&`? If you use the latter you can chain the call. – NathanOliver Jun 27 '17 at 17:13
  • Why not just return a `std::string` by value? Generally, value semantics are nice both on input and output (easier to reason about lifetimes) and the compiler is highly likely to optimize it (RVO) & besides, you are going to pay for a copy *anyway* once you hit `push_back`.. not trying to be annoying; really currious as to your reason for using a `const&` return value here (I might learn something). – Jesper Juhl Jun 27 '17 at 17:17
  • @NathanOliver -- that's more from a general sense of cleanliness. I don't like trafficking in references to modifiable data when it isn't part of the design. The goal here is to push it back, and that works just fine with a `const&`. – Pete Becker Jun 27 '17 at 17:17
  • @JesperJuhl You can't RVO here as `var` is a reference. @pete sounds good. – NathanOliver Jun 27 '17 at 17:19
  • 1
    @JesperJuhl - yes, you're going to pay for a copy in the push_back, but that doesn't justify paying for **another** copy in the return. I generally view function calls involving values and `const&`s as more or less semantically equivalent, and prefer references because they don't involve copying. It's nice if the compiler can identify unnecessary copies, but it's even nicer if it doesn't have to. – Pete Becker Jun 27 '17 at 17:20
  • @NathanOliver D'oh, my bad. – Jesper Juhl Jun 27 '17 at 17:22
  • @Pete Becker thank you for explaining your reasoning. – Jesper Juhl Jun 27 '17 at 17:23