[英]Different between move and forward in this example
The first example that take A by value does two moves and the one by refref only does one move.第一个按值取 A 的示例执行两次移动,而按 refref 取值的示例仅执行一次移动。 What is the difference?
有什么不同?
struct A
{
A() { cout << "constructor" << endl;}
A(const A&) { cout << "copy constructor " << endl;}
void operator=(const A&) { cout << "assignment operator" << endl; }
A( A&&) { cout << "move copy constructor" << endl;}
void operator=(A&&) { cout << "move assignment operator" << endl;}
};
struct C {
void func(A t) {
d.a = std::move(t);
}
struct Data {
A a;
};
Data d;
};
struct B {
void func(A t) {
C c;
c.func(std::move(t));
}
};
//////////////////////////////////////////////////////////
struct C {
template<class T>
void func(T&& t) {
d.a = std::forward<T>(t);
}
struct Data {
A a;
};
Data d;
};
struct B {
template<class T>
void func(T&& t) {
C c;
c.func(std::forward<T>(t));
}
};
From cppreference.com :从cppreference.com :
When used according to the following recipe in a function template, forwards the argument to another function exactly as it was passed to the calling function.
在函数模板中根据以下配方使用时,将参数完全按照传递给调用函数的方式转发给另一个函数。
template<typename T> wrapper(T&& arg) { foo(std::forward<T>(arg)); }
So in your snippet所以在你的片段中
struct B {
template<class T>
void func(T&& t) {
C c;
c.func(std::forward<T>(t));
}
};
The std::foward<T>(t)
will simply forward your T&&
object to c.func()
exactly as B::func()
was called. std::foward<T>(t)
只会像调用B::func()
一样简单地将您的T&&
对象转发到c.func()
。 This doesn't require a move, which is why you are seeing fewer moves using std::forward<T>
.这不需要移动,这就是为什么您使用
std::forward<T>
看到更少的移动。
I would really recommend checking out Scott Meyer's blog post on this topic of std::move
and std::forward
: http://scottmeyers.blogspot.com/2012/11/on-superfluousness-of-stdmove.html我真的建议查看 Scott Meyer 关于
std::move
和std::forward
主题的博客文章: http : //scottmeyers.blogspot.com/2012/11/on-superfluousness-of-stdmove.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.