为什么只有在向量中已经有一个元素时才调用移动构造函数?
Why is the move constructor only called when there is already an element in the vector?
我正在尝试学习C++11中的新功能。我正在XCode中测试以下代码。
#include <iostream>
#include <string>
#include <vector>
class CClass
{
std::string s;
public:
CClass()
{
std::cout<<"Default Constructor"<<std::endl;
}
CClass(const std::string v) :s(v) {
std::cout<<"Constructor"<<std::endl;
}
CClass(const CClass& other): s(other.s) {
std::cout<<"Copy Constructor"<<std::endl;
}
CClass(CClass&& a) noexcept
{
std::cout<<"Move Constructor"<<std::endl;
s = std::move(a.s);
}
CClass& operator = (const CClass& other)noexcept
{
std::cout<<"Copy Assignment"<<std::endl;
if(this != &other)
{
s = other.s;
}
return *this;
}
CClass& operator = (CClass&& other) noexcept
{
std::cout<<"Move Assignment"<<std::endl;
if(this != &other)
{
s = std::move(other.s);
}
return *this;
}
};
int main()
{
std::vector<CClass> v;
CClass x("hello");
//v.push_back(x);
std::cout<<"--------------------"<<std::endl;
v.emplace_back("uiuiu");
std::cout<<"--------------------"<<std::endl;
}
当我取消注释推送时,我得到以下结果:
Constructor
Copy Constructor
--------------------
Constructor
Move Constructor
--------------------
否则,如果我评论它,我会得到:
Constructor
--------------------
Constructor
--------------------
我的问题是为什么在第二种情况下不调用移动构造函数?仅在第一种情况下,当 vector 最初不为空时,才会调用它。
这是因为向量中的一个元素需要移动到新的内存位置。发生这种情况的原因是新大小将超过矢量容量,因此必须为矢量分配具有新容量的新内存。
从std::vector::emplace_back
:
如果新
size()
大于capacity()
则所有迭代器和引用(包括过去结束的迭代器(都将失效。否则,只有过去结束迭代器失效。
迭代器和引用因同样的原因而失效:因为这些元素现在存储在内存中的新位置。
如果在第一种情况下调用reserve
,您将看到没有调用任何移动构造函数:
CClass x{"hello"}; // constructor
v.reserve(2); // make space for 2 elements (you could have also used resize)
v.push_back(x); // copy constructor
v.emplace_back("uiuiu"); // constructor
相关文章:
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- 使用并行参数向量调用元素向量的成员函数
- 调用 erase() 函数是否也会在擦除元素之前更改迭代器值?
- 如何在不迭代的情况下对数组中的每个元素调用方法
- 为什么 delete[] 不等同于 C++ 中为每个元素调用 delete?
- C++为每个元素调用任意函数
- C 如何使用数组的元素调用类
- boost::lockfree-为排队的元素调用析构函数
- 如何使用提升 lambda 对集合中的每个元素调用方法?
- 为集合中的每个元素调用具有多个参数的函数
- 对C++向量的每个元素调用函数
- 为构造的std::vector中的每个元素调用默认构造函数
- c++11:用向量的元素调用变差函数
- 对std::array中的元素调用用户定义的构造函数
- 对一个对象上的每个元组元素调用函数,不进行递归
- 当每个字符串由"new char[]"创建时,如何对"vector<string>"的元素调用"delete"?
- 作为数组元素调用函数
- std::list 的擦除成员函数是否为所有存储的元素调用析构函数?
- 对集合中的每个元素调用print的通用算法