emplace操作是C++11新特性,新引入的的三個成員emlace_front、empace 和 emplace_back,這些操作構造而不是拷貝元素到容器中,這些操作分别對應push_front、insert 和push_back,允許我們将元素放在容器頭部、一個指定的位置和容器尾部。
兩者的差別
當調用insert時,我們将元素類型的對象傳遞給insert,元素的對象被拷貝到容器中,而當我們使用emplace時,我們将參數傳遞元素類型的構造函,emplace使用這些參數在容器管理的記憶體空間中直接構造元素。
一個例子
MyString.h
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
class MyString
{
public:
MyString(const char *str = NULL);// 普通構造函數
MyString(const MyString &other);// 拷貝構造函數
~MyString(void);// 析構函數
MyString & operator = (const MyString &other);// 指派函數
private:
char *m_data;// 用于儲存字元串
};
#endif // MYSTRING_H
MyString.cpp
#include "MyString.h"
#include <iostream>
#include <string.h>
//普通構造函數
MyString::MyString(const char *str)
{
if (str == NULL)
{
m_data = new char[1];
*m_data = '\0';
}
else
{
int length = strlen(str);
m_data = new char[length + 1];
strcpy(m_data, str);
}
std::cout<<"construct:"<<m_data<<std::endl;
}
// String的析構函數
MyString::~MyString(void)
{
std::cout<<"deconstruct:"<<m_data<<std::endl;
delete[] m_data;
}
//拷貝構造函數
MyString::MyString(const MyString &other)
{
int length = strlen(other.m_data);
m_data = new char[length + 1];
strcpy(m_data, other.m_data);
std::cout<<"copy construct:"<<m_data<<std::endl;
}
//指派函數
MyString & MyString::operator = (const MyString &other)
{
std::cout<<"copy assignment"<<std::endl;
if (this == &other)
return *this;
if (m_data)
delete[] m_data;
int length = strlen(other.m_data);
m_data = new char[length + 1];
strcpy(m_data, other.m_data);
return *this;
}
main.cpp
#include <vector>
#include "MyString.h"
int main()
{
{
std::cout<<"++++++++++++++++++++++++++++++++++"<<std::endl;
std::vector<MyString> vStr;
// 預先配置設定,否則整個vector在容量不夠的情況下重新配置設定記憶體
vStr.reserve(100);
vStr.push_back(MyString("can ge ge blog"));
}
{
std::cout<<"++++++++++++++++++++++++++++++++++"<<std::endl;
std::vector<MyString> vStr;
// 預先配置設定,否則整個vector在容量不夠的情況下重新配置設定記憶體
vStr.reserve(100);
vStr.emplace_back("hello world");
}
system("pause");
return 0;
}