重复调用 f(T&& t) 形式的函数而不使用 std::move(t) ?
Call functions in the form f(T&& t) repeatedly without using std::move(t) again?
#include <iostream>
#include <cstdlib>
#include "A.h"
void second(const A& a)
{
std::cout << "void second(const A& a)." << std::endl;
}
void second(A&& a)
{
std::cout << "void second(A&& a)." << std::endl;
}
void first(const A& a)
{
std::cout << "void first(const A& a)." << std::endl;
second(a);
}
void first(A&& a)
{
std::cout << "void first(A&& a)." << std::endl;
second(a); //Make this call void second(A&& a) without using std::move(a) again?
}
int main()
{
std::cout << "int main()." << std::endl;
A a;
first(std::move(a));
std::cin.sync();
std::cin.get();
return EXIT_SUCCESS;
}
second(a);
它不能调用second(A&&)
,因为a
是左值(因为它有一个名称)。
调用second(A&&)
需要一个右值。因此,您需要将a
转换为右值,为此您必须使用move
或进行手动显式转换:
second(std::move(a)); //invokes second(A&&)
second(static_cast<A&&>(a)); //invokes second(A&&)
希望对你有帮助。
您是否发现为每个函数编写右值引用重载的过程很乏味,正在寻找一种方法来避免这种乏味?考虑将你的重载压缩成一个函数,该函数按值获取参数,然后将它们移动到需要的地方。
所以,换句话说,这两个函数…
void foo(X const& x) {
bar(x);
}
void foo(X&& x) {
bar(std::move(x));
}
…变成这个函数
void foo(X x) {
bar(std::move(x));
}
对于每一个额外的参数,节省(在类型和可维护性方面)会成倍增加。它有时需要额外的移动,但从不需要额外的复制(当然,除非没有move构造函数)。
函数内部
void first(A&& a)
参数a
是一个命名值,因此是左值。
你真的不希望它在第一次函数调用时被移走,因为如果你想在函数中多次使用a
,这会造成很多麻烦。考虑
void first(A&& a)
{
second(a);
third(a);
fourth(a);
}
您不希望调用second
将值从a
移开。
相关文章:
- Usages of std::move
- 在C++中对T*类型执行std::move的意外行为
- 关于std::move的使用,是否有编译警告
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 通过实例理解std::move及其目的
- 返回一个带有 std::move 的对象并链接函数
- 当 std::move 与 C 样式数组或不移动对象时会发生什么
- std::move a const std::vector in a lambda capture
- "std::forward"和"std::move"真的不生成代码吗?
- 如何在没有 std::move 的情况下移动临时对象
- 关于在成员重载中使用 std::move() 的问题
- 显式清除 std::move 之后的源资源
- std::move 如何使原始变量的值无效?
- 复制elision、std::move和链式函数调用
- 如果真的需要std::move,我们应该什么时候声明右值refs
- 使用std::move将std::unique_ptr作为qt信号参数传递
- 无法使用带有 std::move 的自定义删除器插入 std::unique_ptr
- C++:我应该在 return 语句中显式使用 std::move() 来强制移动吗?
- 编译器是否足够聪明,以至于 std::move 变量超出范围?
- std::move() 或其在局部变量上的显式等价物可以允许 elision 吗?