Binding temporaries to references

95 Views Asked by At

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.

0

There are 0 best solutions below