C++笔记——emplace_back的用法
概要:
emplace内部实现是多参数模板,保证在插入对象的时候,直接插入构造函数的参数列表。如下例子中,自定义类C的插入
#include <iostream> #include <thread> #include <unistd.h> //休眠时间 #include <vector> using namespace std; void hello(int n){ sleep(1); cout << "hello concurrent thread " << n << endl; } class B; class A{ public: A(){ cout << "A is construction. " << endl; } ~A(){ cout << "A is deconstruction. " << endl; } //shared_ptr<B> pa; weak_ptr<B> pa; }; class C{ public: //构造函数带参数列表 C(int a, int b, int c): name(a), habby(b), age(c){ cout << "a = " << a << " b = " << b << " c = " << c << endl; } //构造函数内为成员参数赋值 /* C(int a, int b, int c) { cout << "a = " << a << " b = " << b << " c = " << c << endl; name = a; habby = b; age = c; }*/ int name; int habby; int age; }; class B{ public: B(){ cout << "B is construction. " << endl; } ~B(){ cout << "B is deconstruction. " << endl; } //shared_ptr<A> pb; weak_ptr<A> pb; }; int main(){ /* * 、//多线程对象的使用 thread t(hello, 3); cout << "main thread 1. " << endl; //sleep(1); // t.detach(); t.join(); cout << "main thread 2 " << endl; */ /* //shared_ptr的循环引用 std::shared_ptr<A> sa = std::make_shared<A>(); std::shared_ptr<B> sb = std::make_shared<B>(); sa->pa = sb; sb->pb = sa; std::cout << "B expired = " << sa->pa.expired() << std::endl; std::cout << "A expired = " << sb->pb.expired() << std::endl;*/ //测试emplace_back和push_back vector<C> vec; vec.emplace_back(1,2,3);//正确 //vec.push_back(1,3,2); //报错 vec.push_back(C(12,13,15));//正确 vec.emplace_back(C(6,7,8));//正确 return 0; }
而push_back 不能直接将多个构造参数加进去。
直接插入对象C(6,7,8),这个操作调用了拷贝构造函数,整个过程是先生成C(6,7,8)临时对象,然后拷贝到构造函数的形参中,最后释放临时对象。效率上emplace_back更高。
注:在内置类型下,两者都是一样的效率。都是直接插入,没有拷贝。
作者:水水滴答
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。