【问题标题】:I want to bind a a non-const lvalue reference to type T to a temporary of type T我想将对类型 T 的非常量左值引用绑定到类型 T 的临时值
【发布时间】:2020-11-05 02:13:08
【问题描述】:

有什么技巧/演员可以让我这样做吗?

#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 采用非 const 引用之外的函数是否有办法完成该任务。

【问题讨论】:

  • 相关:getBar().swap(foo)呢?
  • 如果您考虑到交换以外的功能,那么解决您的问题会容易得多。有没有我们可以解决的具体问题场景?
  • 只要foo = getBar();。它会做正确的事
  • 这似乎是右值引用的用途。

标签: c++ rvalue temporary const-correctness


【解决方案1】:

你可以定义一个辅助函数,std::move的“相反”

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

在您的情况下,纯右值将具体化为一个绑定到右值引用的 xvalue,这让我们可以构造一个引用同一对象的左值。

foo.swap(stay(getBar());

像往常一样,临时文件会一直存在到完整表达式的末尾(分号),所以这是安全的(假设 swap 不会尝试将引用保存在某处)。

【讨论】:

    猜你喜欢
    • 2019-12-21
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    • 2021-03-03
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多