提问者:小点点

我想将类型T的非常量值引用绑定到类型T的临时


有什么戏法/演员让我这么做吗?

#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;
}

在这种具体情况下

foo = getBar(); 

是个好答案。 我想知道除了swap使用非常量引用之外,是否还有其他方法来完成该任务。


共1个答案

匿名用户

您可以定义一个辅助函数,即std::move的“对立面”

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

在您的示例中,prvalue将具体化为绑定到rvalue引用的xvalue,这允许我们构造引用相同对象的lvalue。

foo.swap(stay(getBar());

与通常一样,临时函数一直存在到完整表达式的结尾(分号),因此这是安全的(假设swap不试图将引用保存在某个地方)。