【发布时间】: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