所以,我做了一个这样的课程,并推出了main:
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
为什么当"testing_var3“由fun1返回时,会使用移动构造函数?为什么会有这样的差别,当类型的扣减是由汽车而不是自动&&?
我以为会使用移动作业,但是在fun1中的移动构造函数对我来说是无稽之谈.
以及为什么在fun2中使用移动构造函数?不应该是搬家吗?
/EDIT:
我向构造函数和析构函数添加了一些额外的代码。现在我明白了:
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?
发布于 2015-02-12 21:42:43
为什么当"testing_var3“由fun1返回时,会使用移动构造函数?
testing_var3
被推断为my_class
类型,因此必须调用一个构造函数来创建一个新的my_class
对象。因为右边是临时的,所以选择了移动构造函数。
为什么会有这样的差别,当类型的扣减是由汽车而不是自动&&?
如果使用auto&&
,则始终声明引用,当类引用绑定到同一类类型的表达式时,不调用构造函数,因为没有创建新对象。auto
从不声明引用。
我以为会使用移动作业,但是在fun1中的移动构造函数对我来说是无稽之谈. 以及为什么在fun2中使用移动构造函数?不应该是搬家吗?
没有赋值,只需复制初始化。在……里面
T x = e;
T x = braced-init-list;
尽管出现了=
令牌,但不调用赋值运算符。这是初始化而不是分配。赋值要求已构造的对象被赋值.
发布于 2015-02-12 21:44:37
testing_var3
由移动ctor构造,最后返回值由移动ctor构造。
fun2
中没有赋值,只有需要构造/初始化的返回值。
发布于 2015-02-12 22:26:14
我建议您阅读Scott关于“通用参考资料”的博客。auto&&可以绑定到lvalue或rvalue。在大多数情况下,您不需要使用auto&&,除非您真正知道自己在做什么。
https://stackoverflow.com/questions/28488265
复制相似问题