[原创](Modern C++)现代C++的std::vector的emplace_back()与push_back()的区别

[简介]

常用网名: 猪头三

出生日期: 1981.XX.XX

QQ联系: 643439947

个人网站: 80x86汇编小站 https://www.x86asm.org

编程生涯: 2001年~至今[共22年]

职业生涯: 20年

开发语言: C/C++、80x86ASM、PHP、Perl、Objective-C、Object Pascal、C#、Python

开发工具: Visual Studio、Delphi、XCode、Eclipse、C++ Builder

技能种类: 逆向 驱动 磁盘 文件

研发领域: Windows应用软件安全/Windows系统内核安全/Windows系统磁盘数据安全/macOS应用软件安全

项目经历: 磁盘性能优化/文件系统数据恢复/文件信息采集/敏感文件监测跟踪/网络安全检测

[序言]

(Modern C++)现代C++中, 新增了emplace_back()方法, 比push_back()的效率更高. 它们差别在于emplace_back()方法避免了拷贝(copy)和移动(move)的开销. 下面的代码可以演示出, 当调用emplace_back()方法追加元素的时候, 并没有触发类的拷贝构造函数.

[代码演示, 在C++ Builder 12环境下编写]

cpp 复制代码
class President
{
    std::wstring mpr_str_Name;
    std::wstring mpr_str_Country ;
    int mpr_int_Year ;

public:

    President(std::wstring str_param_Name, std::wstring str_param_Country, int int_param_Year):mpr_str_Name(std::move(str_param_Name)),
    mpr_str_Country(std::move(str_param_Country)), mpr_int_Year(std::move(int_param_Year))
    {
        Form1->Memo1->Lines->Add(L"I am being constructed!") ;
    }


    President(President&& class_param_Other):mpr_str_Name(std::move(class_param_Other.mpr_str_Name)),
    mpr_str_Country(std::move(class_param_Other.mpr_str_Country)), mpr_int_Year(class_param_Other.mpr_int_Year)
    {
        Form1->Memo1->Lines->Add(L"I am being moved!") ;
    }

    President& operator=(const President& class_param_Other)=default ;
};

void __fastcall TForm1::Bn_DemoClick(TObject *Sender)
{
    std::vector<President> vector_Elections ;
    Form1->Memo1->Lines->Add(L"emplace_back") ;
    vector_Elections.emplace_back(L"Nelson Mandela", L"South Africa", 1994);

    Form1->Memo1->Lines->Add(L"") ;

    std::vector<President> vector_Elections_Other ;
    Form1->Memo1->Lines->Add(L"push_back") ;
    vector_Elections_Other.push_back(President(L"Franklin Delano Roosevelt", L"the USA", 1936)) ;
}

[结尾]

注意上面的演示代码, emplace_back(L"Nelson Mandela", L"South Africa", 1994) 和 push_back(President(L"Franklin Delano Roosevelt", L"the USA", 1936)) 的写法差异, emplace_back()可以直接构造元素.

相关推荐
艾莉丝努力练剑几秒前
【Linux网络】Linux 网络编程:HTTP(三)HTTP 协议原理
linux·运维·服务器·网络·c++·http
薇茗4 分钟前
【初阶数据结构】 升沉有序的平仄 排序 3
c语言·开发语言·数据结构·算法·排序算法·文件归并排序
字节高级特工6 分钟前
C++11(一) 革新:右值引用与移动语义
java·开发语言·c++·人工智能·后端
叶之香9 分钟前
一次 Kingston U 盘重定向中获取 Device Descriptor 超时问题排查
c++·windows·visual studio
UestcXiye9 分钟前
GoogleTest 使用指南 | 单元覆盖率分析
c++·单元测试·googletest
AI科技星11 分钟前
强哥德巴赫猜想(1+1)终极证明(2026 年5月 21 日)
开发语言·人工智能·算法·计算机视觉·量子计算
王老师青少年编程13 分钟前
csp信奥赛C++高频考点专项训练之前缀和&差分 --【一维前缀和】:“非常男女”计划
c++·前缀和·csp·高频考点·信奥赛·“非常男女”计划
故事和你9116 分钟前
洛谷-【图论2-4】连通性问题2
开发语言·数据结构·c++·算法·动态规划·图论
Brilliantwxx17 分钟前
【C++】 二叉搜索树
开发语言·c++·算法
为何创造硅基生物9 小时前
C语言 结构体内存对齐规则(通俗易懂版)
c语言·开发语言