C++11新特性之十一:emplace

版权声明:本文为灿哥哥http://blog.csdn.net/caoshangpa原创文章,转载请标明出处。 https://blog.csdn.net/caoshangpa/article/details/80388994

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;
}

输出结果


从结果可以看出,vStr.push_back(MyString("can ge ge blog")) 这个语句首先执行了构造函数,构造一个临时对象,接着执行拷贝构造将临时对象复制到vector,最后销毁临时对象和vector中的元素。而emplace_back只调用一次构造函数和一次析构函数。两相对比,效率上的提高不言而喻

猜你喜欢

转载自blog.csdn.net/caoshangpa/article/details/80388994