C编译器如何决定何时为std :: vector或任何对象调用移动构造函数
发布时间:2020-12-16 10:13:18 所属栏目:百科 来源:网络整理
导读:参见英文答案 What are move semantics?????????????????????????????????????11个 我正在阅读std模板库书,并与STL Containers章节中列出的以下详细信息混淆. 显然,它指定了STD :: VECTOR操作和效果 Operation EffectvectorElem c(c2) | Copy constructor; c
参见英文答案 >
What are move semantics?????????????????????????????????????11个
我正在阅读std模板库书,并与STL Containers章节中列出的以下详细信息混淆. 显然,它指定了STD :: VECTOR操作和效果 Operation Effect vector<Elem> c(c2) | Copy constructor; creates a new vector as a copy of c2 (all elements are copied) vector<Elem> c = c2 | Copy constructor; creates a new vector as a copy of c2 (all elements are copied) vector<Elem> c(rv) | Move constructor; creates a new vector,taking the contents of the rvalue rv (since C++11) vector<Elem> c = rv | Move constructor; creates a new vector,taking the contents of the rvalue rv (since C++11) 显然,移动和复制构造函数的语法没有区别,当它们被调用时? 解决方法
假设你有一个函数f,它按值返回一个向量:
std::vector<int> f(); 函数返回的值是rvalue. 然后让我们说你想调用这个函数来初始化你的向量: std::vector<int> v = f(); 现在编译器知道f返回的向量将不再被使用,它是一个临时对象,因此复制这个临时对象没有意义,因为它无论如何都会立即被破坏.因此编译器决定调用move-constructor. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |