在读vins-mono的代码里,在estimate_node.cpp里看到了std::pair,之前没怎么用过,于是做个笔记。
先看一下api
看一下,很简单,就是把两个类型任意对象配对。
在vins-mono的estimator.cpp里,用它来实现的功能是实现imu msg和pclmsg的配对。并放在vector里存储。
值得关注的是,在这种情况下,往vector里存储时,使用emplace_back而不是push back可以简化操作。
为什么这么说?
写了一个函数测试一下,使用vector时,只能存放左值,比如下图这么用,就会报错。我们不能用push_back,在push的同时构造对象。而用emplace_back就可以
我总结了一下push back 和emplace_back存放物体的过程区别
push_back()
a) A constructor is called to create the temporary object
b) A copy of the temporary object is created in the vector
c) After copying the object the destructor is called to destory the temporary object
Emplace_back: the object is created directly in the vector 。
用下面代码可以看出。请观察destructor触发的时机
class A{
int i;
public:
A(int ii):i(ii) { cout<<"\nA constructor called!!"; }
~A() { cout<<"\nA destructor called!!"; }
};
class B{
int i;
int j;
public:
B(int ii, int jj):i(ii),j(jj){cout<<"B constructor called";}
~B(){ cout<<"\nB destructor called!!";}
};
void test1()
{
std::vector<A> v;
v.emplace_back(78);
cin.get();
}
void test2()
{
std::vector<B> v;
v.emplace_back(12,12);
cin.get();
}
int main()
{
test2();
return 0;
}