为什么你使用std :: move当你有&&在C ++ 11? [英] Why do you use std::move when you have && in C++11?

查看:201
本文介绍了为什么你使用std :: move当你有&&在C ++ 11?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我最近参加了一个C ++ 11研讨会,并给出了以下建议。

I recently attended a C++11 seminar and the following tidbit of advice was given.

when you have && and you are unsure, you will almost always use std::move

您应该使用 std :: move 而不是某些替代方案,以及在您不应使用 std :: move

Could any one explain to me why you should use std::move as opposed to some alternatives and some cases when you should not use std::move?

推荐答案

首先,我会解决的问题可能有一个误解:

每当你看到 T&& t 在代码中(And T是一个实际类型,而不是模板类型),记住 t 的值类别是一个左值),而不是右值(临时)。这很混乱。 T&&& 仅表示 t 可以 $ rvalue 1 ,但 t 本身是一个左值,而不是右值。如果它有一个名称(在这种情况下, t ),那么它是一个左值,不会自动移动,但如果没有名称(结果 3 + 4 ),那么它是一个右值,并且会自动移动到它的结果中。 (在这种情况下 T&& )几乎与变量的值类别无关(在这种情况下, )。

First, there's probably a misconception in the question I'll address:
Whenever you see T&& t in code (And T is an actual type, not a template type), keep in mind the value category of t is an lvalue(reference), not an rvalue(temporary) anymore. It's very confusing. The T&& merely means that t can be constructed from an object that was an rvalue 1, but t itself is an lvalue, not an rvalue. If it has a name (in this case, t) then it's an lvalue and won't automatically move, but if it has no name (the result of 3+4) then it is an rvalue and will automatically move into it's result if it can. The type (in this case T&&) has almost nothing to do with the value category of the variable (in this case, an lvalue).

话虽如此,如果你有 T&& t 写入您的代码,这意味着您有一个变量的引用, 是一个临时的,如果你愿意,可以销毁。如果您需要多次访问该变量,您可以不要> cd> cd>,否则会丢失它的值。但是,最后一次你接受 t 它是安全的 std :: move 它的值到另一个 T 。 (95%的时间,这是你想做的)

That being said, if you have T&& t written in your code, that means you have a reference to a variable that was a temporary, and it is ok to destroy if you want to. If you need to access the variable multiple times, you do not want to std::move from it, or else it would lose it's value. But the last time you acccess t it is safe to std::move it's value to another T if you wish. (And 95% of the time, that's what you want to do)

1。如果 T 是模板类型,则 T&& 是一个通用引用,在这种情况下,您使用 std :: forward< T>(t)而不是 std :: move(t)请参见此问题

1. if T is a template type, T&& is a universal reference instead, in which case you use std::forward<T>(t) instead of std::move(t) the last time. See this question

这篇关于为什么你使用std :: move当你有&amp;&amp;在C ++ 11?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆