![](/img/trans.png)
[英]What's the difference between “auto v = f()” and “auto&& v = f()”?
[英]Difference between auto&& and auto
所以,我做了这样一个课程,并推出了主要的:
class my_class{
public:
my_class(): status("constructor"){
cout << "constructor" << endl;
}
my_class(my_class&& obj): status("move constructor"){
cout << "move constructor" << endl;
}
my_class(const my_class& obj): status("copy constructor"){
cout << "copy constructor" << endl;
}
my_class& operator=(my_class&& obj){
cout << "move assignment" << endl;
return *this;
}
my_class& operator=(const my_class& obj){
cout << "copy assignment" << endl;
return *this;
}
~my_class(){
cout << "destructor; " << "object made by: " << status << endl;
}
string status;
};
my_class&& fun1(my_class&& temp){
cout << "inside fun1" << endl;
return move(temp);
}
my_class fun2(my_class&& temp){
cout << "inside fun2" << endl;
return move(temp);
}
int main(){
auto&& testing_var1 = fun1(my_class{});
auto&& testing_var2 = fun2(my_class{});
auto testing_var3 = fun1(my_class{});
auto testing_var4 = fun2(my_class{});
return 0;
}
我真的让我感到惊讶的是:
constructor
inside fun1
constructor
inside fun2
move constructor
constructor
inside fun1
move constructor
constructor
inside fun2
move constructor
为什么当fun1返回“testing_var3”时,会使用移动构造函数? 为什么会有这样的差异,当通过auto not auto &&进行类型推导时?
我以为会使用移动赋值,但是fun1中的移动构造函数对我来说是无意义的...
为什么移动构造函数在fun2中使用? 不应该移动任务吗?
/编辑:
我为构造函数和析构函数添加了一些额外的代码。 现在我得到:
constructor
inside fun1
destructor; object made by: constructor
constructor
inside fun2
move constructor
destructor; object made by: constructor
constructor
inside fun1
move constructor
destructor; object made by: constructor
constructor
inside fun2
move constructor
destructor; object made by: constructor
destructor; object made by: move constructor
destructor; object made by: move constructor
destructor; object made by: move constructor
而我的下一个问题是:为什么第一个变量是悬空引用而另一个不是? 为什么第二个变量不是这样的参考,如@MattMcNabb建议的那样?
为什么当fun1返回“testing_var3”时,会使用移动构造函数?
testing_var3
推导为类型my_class
,因此构造必须调用以创建一个新my_class
对象。 由于右侧是临时的,因此选择了移动构造函数。
为什么会有这样的差异,当通过auto not auto &&进行类型推导时?
如果使用auto&&
那么总是声明一个引用,并且当对类的引用绑定到同一类类型的表达式时,不会调用构造函数,因为没有创建新对象。 auto
永远不会声明引用。
我以为会使用移动赋值,但是fun1中的移动构造函数对我来说是无意义的...
为什么移动构造函数在fun2中使用? 不应该移动任务吗?
没有任务分配; 只是复制初始化 。 在
T x = e;
T x = braced-init-list;
尽管出现了=
token,但不会调用赋值运算符。 这是初始化,而不是分配。 赋值需要已分配的已构造对象。
testing_var3
由move ctor构造,最后一个返回值由move ctor构造...
在fun2
没有赋值只需要构造/初始化的返回值。
我建议你阅读Scott Meyers关于“Universal References”的博客 。 auto &&可以绑定到左值或右值。 在大多数情况下,除非你真的知道自己在做什么,否则你不需要使用auto &&。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.