emplace_back和push_back区别,以及vector内存变化
程序员文章站
2022-03-21 17:40:02
...
void* operator new(size_t size)//重载operator new
{
cout << "vector size to: " << size/sizeof(int) << endl;
return malloc(size);
}
class test {
public:
test() :num(0) { cout << "default construct of " <<0<< endl; };
test(int a) :num(a) { cout << "assign construct of " <<a<<endl; };
test(test&& t) :num(t.num) { cout << "move construct of " << t.num<< endl; };
test(const test& t) :num(t.num) { cout << "copy construct of " << t.num<< endl; };//参数前必须加const否则会报错
//如果不定义,会调用默认的拷贝构造 copy bitwise
~test()
{
cout << "deconstruct" << endl;
};
private:
int num;
};
int main()
{
vector<test> a;
//https://blog.csdn.net/LiQian06336/article/details/99181398
cout << "test" << sizeof(test) << endl;
cout << "vector size in memory: " << sizeof(a) << endl;
cout << "vector capacity: " << a.capacity() << endl;
a.push_back(1);
cout << "vector capacity: " << a.capacity() << endl;
a.emplace_back(2);
/cout << "vector capacity: " << a.capacity() << endl;
a.push_back(test(3));
cout << "vector capacity: " << a.capacity() << endl;
a.emplace_back(test(4));
cout << "vector capacity: " << a.capacity() << endl;
}
运行结果,
vector size to: 2
test4
vector size in memory: 16//刚开始会申请内存,用于存放指针,见main函数中的链接
vector capacity: 0//正式开始
assign construct of 1//push_back(1),先构造临时对象
vector size to: 1//再申请内存
move construct of 1//再调用移动构造
deconstruct//销毁临时对象
vector capacity: 1
vector size to: 2//empalce_back,先申请内存,申请的是原来大小的两倍,因为vector要扩容,扩容不是原地扩,而是新找一个更大的地方
assign construct of 2//再在申请得到的新内存上原地构造
copy construct of 1//因为vector的容量由1变为2,需要将原来地方的1拷贝过来
deconstruct//将原地方的1析构
vector capacity: 2
assign construct of 3//同1一样,构造临时对象
vector size to: 3//申请内存,扩容
move construct of 3//将3先移动到新的内存地方上
copy construct of 1//将剩余的移动过来
copy construct of 2
deconstruct//将临时对象3和原来的1和2析构
deconstruct
deconstruct
vector capacity: 3
assign construct of 4
vector size to: 4
move construct of 4//同3
copy construct of 1
copy construct of 2
copy construct of 3
deconstruct
deconstruct
deconstruct
deconstruct
vector capacity: 4
deconstruct
deconstruct
deconstruct
deconstruct
结论:
- emplace_back和push_back区别在与以参数传入的时候
,emplace_back先申请内存,再原地构造,而push_back需要先构造临时对象。 - 对临时对象的处理上,都依赖与是否存在移动构造,若有,则都优先调用移动构造
推荐阅读
-
emplace_back和push_back区别,以及vector内存变化
-
vector中push_back和emplace_back的区别
-
C++11: vector::push_back和vector::emplace_back的区别
-
c++ vector容器emplace_back() 和 push_back 的区别
-
c++ std::vector 使用push_back 和emplace_back的区别
-
C++ vector中push_back()和emplace_back()的区别
-
C++ STL vector添加元素之push_back()和emplace_back()的区别
-
vector中push_back和emplace_back区别