2

Possible Duplicate:
How come a non-const reference cannot bind to a temporary object?

First up, I understand that the standard mandates that temporaries can only be bound to const references, and, as I understand it, in this case the lifetime of the temporary is bound to the lifetime of the reference.

Other than "because the standard says so..." why is it such a good idea to prevent temporaries being bound to general (i.e. non-const) references??

Consider the following, where we have a routine that requires some workspace:

void foo(std::vector<mytype> &data, std::vector<mytype> &work)
{ // we do something to DATA but we need to use the workspace WORK
  // we may resize WORK, write to it, generally use it in a non-const way

  // we want to pass WORK as a parameter because we want to have the option
  // of pre-allocating it (for efficiency, FOO may, but is not always, called
  // inside a loop)
}

Why would it be so evil to make an isolated call to foo as follows:

// case 1
// DATA already created elsewhere
foo(data, std::vector<mytype>() );

Of course we could do something like this:

// case 2
// DATA already created elsewhere
std::vector<mytype> work;
foo(data, work);

But then the lifetime of work is extended until the end of the enclosing block, which can be unwanted.

I know that there are ways to work around this kind of thing, but case 1 here would be a neat way of doing things, except we're not allowed.

Community
  • 1
  • 1
Darren Engwirda
  • 6,915
  • 4
  • 26
  • 42
  • Why not write `void foo(std::vector &work; foo(data, work); }` ? – Chris Lutz Jun 30 '11 at 02:13
  • 3
    Already asked: http://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object – torahmike Jun 30 '11 at 02:14
  • @Chris: I agree that would work in this case, but I'm more interested in why the standard forbids patterns like case 1, not workarounds for this particular example. – Darren Engwirda Jun 30 '11 at 02:21
  • @torahmike: similar, but I think this is a different example where you actually have a good reason to modify a temporary through a reference. – Darren Engwirda Jun 30 '11 at 02:25
  • See [Should this C++ temporary binding to reference member be illegal?](http://stackoverflow.com/questions/1477028/should-this-c-temporary-binding-to-reference-member-be-illegal?). – Ed Staub Jun 30 '11 at 02:28

0 Answers0