class Test { public: Test(int) { cout << "Test(int)" << endl; } Test(int, int) { cout << "Test(int, int)" << endl; } Test(const Test&) { cout << "Test(const Test&)" << endl; } Test(Test &&) { cout << "Test(Test &&)" << endl; } ~Test() { cout << "~Test()" << endl; } }; //容器的空间配置器 template<typename T> class MyAllocator { //allocate deallocate //construct destory T* allocate(size_t size) { return (T*)malloc(size * sizeof(T)); } template<typename... Types> void construct(T* ptr, Types&&... args) { //args只是一个参数,而且是个Test对象,T也是Test类型 new (ptr) T(std::forward<Types>(args)...); } }; template<typename T, typename Alloc = MyAllocator<T>> class vector { public: vector() : vec_(nullptr), size_(0), idx_(0) {} //预留内存空间 void reserve(size_t size) { vec_ = allocator_.allocate(size); size_ = size; } void push_back(const T& val) { allocator_.construct(vec_ + idx_, val); idx_++; } void push_back(T&& val) { allocator_.construct(vec_ + idx_, std::move(val)); idx_++; } //1.引用折叠 template<typename... Types> void emplace_back(Types&&... args) { //不管是左值引用、右值引用变量,它本身是个左值。传递的过程中 //要保持args的引用类型(左值的?右值的)类型完美转发forward allocator_.construct(vec_ + idx_, std::forward<Types>(args)...); idx_++; } private: T* vec_; int size_; int idx_; Alloc allocator_; }; int main() { vector<Test> v; v.reserve(100); Test t1(10); cout << "============" << endl; //直接插入对象,两个没有区别 v.push_back(t1); v.emplace_back(t1); cout << "============" << endl; v.push_back(Test(20)); v.emplace_back(Test(20)); cout << "============" << endl; v.push_back(20); //v.push_back(30, 40); cout << "============" << endl; //给emplace传入Test对象构造所需要的参数,直接在容器底层构造对象即可 v.emplace_back(20); v.emplace_back(30, 40); cout << "============" << endl; return 0; }