基本类型情况西,两者几乎没什么区别
但是再自定义类型的时候?emplace——back更高效,但是emplace_back 没有类型检查的安全;只有运行时候才会报错。
#include <vector>
#include <iostream>
using namespace std;
class testDemo
{
public:
explicit testDemo(int num) :num(num) {
std::cout << "call constructor function" << endl;
}
testDemo(const testDemo& other) :num(other.num) {
std::cout << "call copy constructor function" << endl;
}
testDemo(testDemo&& other) :num(other.num) {
std::cout << "call move constructor function" << endl;
}
int getnum()
{
return num;
}
private:
int num;
};
int main()
{
cout << "emplace_back:" << endl;
std::vector<testDemo> demo1;
demo1.emplace_back(2);
cout << demo1[0].getnum() << std::endl;
cout << "push_back:" << endl;
std::vector<testDemo> demo2;
testDemo test(2);
demo2.push_back(test);
}
#-----------------------------------------------------------------------------------------------------------------
#include <vector>
#include <iostream>
using namespace std;
class testDemo
{
public:
explicit testDemo(int num) :num(num) {
std::cout << "call constructor function" << endl;
}
testDemo(const testDemo& other) :num(other.num) {
std::cout << "call copy constructor function" << endl;
}
testDemo(testDemo&& other) :num(other.num) {
std::cout << "call move constructor function" << endl;
}
int getnum()
{
return num;
}
private:
int num;
};
int main()
{
cout << "emplace_back:" << endl;
std::vector<testDemo> demo1;
demo1.emplace_back("asdasd");
cout << demo1[0].getnum() << std::endl;
cout << "push_back:" << endl;
std::vector<testDemo> demo2;
testDemo test(2);
demo2.push_back(test);
}
报错
为什么会高效?
emplace_back:
call constructor function
11
push_back:
call constructor function
call copy constructor function
原理是? 直接再最后构造对象 ,然后push_back 先构造 ,再转移。