I want to bind a a non-const lvalue reference to type T to a temporary of type T

Viewed 102

Is there a trick/cast letting me do that?

#include <vector>

std::vector<int> getBar(){
  std::vector<int> bar (5,200);   // five ints with a value of 200    
  return bar;
}

int main ()
{
  std::vector<int> foo (3,100);   // three ints with a value of 100

  foo.swap(getBar());

  return 0;
}

In this specific case

foo = getBar(); 

is a good answer. I wonder if there is a way to accomplish that task for functions other than swap taking a non const reference.

1 Answers

You can define a auxiliary function, the "opposite" of std::move

template<typename T>
constexpr std::remove_reference_t<T> &stay(T &&t) { // perhaps "temporary" is a better name
    return t;
}

In your case, the prvalue will materialize into an xvalue that binds to an rvalue reference, which lets us construct an lvalue referring to the same object.

foo.swap(stay(getBar());

As usual, the temporary lives until the end of the full-expression (to the semicolon), so this is safe (assuming swap doesn't try to save the reference somewhere).

Related