简单介绍
1、emplace_back 解决了 push_back 在需要进行一次拷贝构造的问题,直接在对应的内存进行构造,避免了拷贝构造。
2、placement new
直接截取最后一段构造的代码,大家可以看到一种语法::new(_p) _T(),这就是 placement new 。在指定的位置进行new。这样就可以在已经申请好的内存上构造。减少了拷贝。
static
_Require<__and_<__not_<__has_construct<_Tp, _Args...>>,
is_constructible<_Tp, _Args...>>>
_S_construct(_Alloc&, _Tp* __p, _Args&&... __args)
{ ::new((void*)__p) _Tp(std::forward<_Args>(__args)...); }
实战
/**
* emplace_back
*/
class Con {
public:
Con(){
}
Con(std::string a, int b, int c) {
std::cout << "Con" << std::endl;
}
Con(const Con & con) {
std::cout << "copy Con" << std::endl;
}
Con(Con && con) {
std::cout << "move Con " << std::endl;
}
};
void test_emplac_back() {
std::vector<Con> vec;
std::string str = "a";
std::cout << "------------push back" << std::endl;
vec.push_back(Con(str,1,1));
std::cout << "------------emplace" << std::endl;
vec.emplace_back(str,1,1);
std::cout << "------------emplace end" << std::endl;
}
int main() {
test_emplac_back();
}
1、看结果,结果发现了,emplace_back 竟然多了一次 copy 构造。why
2、原因还是出在vector 扩容的问题,打印capacity,发现第一加入后确实为1 再次添加时候,出现扩容出现copy Con
3、优化,先让vector 扩容
void test_emplac_back() {
std::vector<Con> vec;
vec.reserve(8); //预留大小
std::string str = "a";
std::cout << "------------push back" << std::endl;
vec.push_back(Con(str,1,1));
std::cout << "capacity " << vec.capacity()<< std::endl;
std::cout << "------------emplace" << std::endl;
vec.emplace_back(str,1,1); //vector 存在扩容时候,会调用copy,而不是emplace
std::cout << "------------emplace end" << std::endl;
}
结果符合预期,bingo