首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >复制变量、创建临时变量和移动语义

复制变量、创建临时变量和移动语义
EN

Stack Overflow用户
提问于 2022-10-01 07:54:09
回答 1查看 98关注 0票数 2

当我看到这个网页https://www.open-std.org/JTC1/SC22/WG21/docs/papers/2006/n2027.html时,我正在学习移动语义和rvalue引用。有一段代码让我困惑。

无移动语义

代码语言:javascript
运行
复制
template <class T> swap(T& a, T& b)
{
    T tmp(a);   // now we have two copies of a
    a = b;      // now we have two copies of b
    b = tmp;    // now we have two copies of tmp (aka a)
}

移动语义

代码语言:javascript
运行
复制
template <class T> swap(T& a, T& b)
{
    T tmp(std::move(a));
    a = std::move(b);   
    b = std::move(tmp);
}

我们如何执行两个副本的a btmp。特别是ab,因为它们是通过引用传递的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-02 01:25:45

让a‘和b’是函数之前的ab中的值。

代码语言:javascript
运行
复制
template <class T> swap(T& a, T& b)
{
  T tmp(a);   // now we have two copies of a' (in a and tmp) and one of b' (in b)
  a = b;      // now we have two copies of b' (in a and b) and one of a' (in tmp)
  b = tmp;    // now we have two copies of a' (in b and tmp) and one of b' (in a)
}

也许能帮上忙。

然后我们做移动版本:

代码语言:javascript
运行
复制
template <class T> swap(T& a, T& b)
{
  T tmp(std::move(a)); // a' is in tmp; b' is in b; a is moved-from
  a = std::move(b);    // a' is in tmp, b' is in a; b is moved-from
  b = std::move(tmp);  // a' is in b; b' is in a; tmp is moved-from
}

诀窍是区分变量a和存储在a中的值。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73916679

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档