当前位置:首页 > 芯闻号 > 充电吧
[导读]emplace操作是C++11新特性,新引入的的三个成员emlace_front、empace 和 emplace_back,这些操作构造而不是拷贝元素到容器中,这些操作分别对应push_front、

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
#includeclass 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#include//普通构造函数
MyString::MyString(const char *str)
{
    if (str == NULL)
    {
        m_data = new char[1];
        *m_data = '';
    }
    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#include "MyString.h"

int main()
{
    {
        std::cout<<"++++++++++++++++++++++++++++++++++"<<std::endl;
        std::vectorvStr;
        // 预先分配,否则整个vector在容量不够的情况下重新分配内存
        vStr.reserve(100);    
        vStr.push_back(MyString("can ge ge blog"));
    }
    {
        
        std::cout<<"++++++++++++++++++++++++++++++++++"<<std::endl;
        std::vectorvStr;
        // 预先分配,否则整个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只调用一次构造函数和一次析构函数。两相对比,效率上的提高不言而喻

本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭