给定一个特征固定大小类型,比如说一个Eigen :: Vector3d,为什么类型不是PoD?底层数据是3个双精度数组,不需要非常重要的构造函数或析构函数。
答案 0 :(得分:2)
模板方面, lot 位(取决于版本)在构造函数中继续,尽管在编译时。虽然所有这些都是在编译时进行评估并因此进行了优化,但仍然存在剩余的空构造函数。如果向POD类型添加空构造函数,则在使用std::copy
时也不会记忆。试试这个:
#include <chrono>
#include <Eigen/Core>
#include <vector>
#include <iostream>
struct notpod
{
notpod() {}
double d[3];
};
struct pod
{
double d[3];
};
using Eigen::Vector3d;
int main(int argc, char** argv)
{
std::chrono::time_point<std::chrono::high_resolution_clock > start, end;
int sz = 20000000;
{
std::vector<pod> a(sz), b(sz);
start = std::chrono::high_resolution_clock ::now();
std::copy(a.begin(), a.end(), b.begin());
end = std::chrono::high_resolution_clock ::now();
std::cout << " POD vector copy took " << (std::chrono::duration<double>(end - start)).count() << " seconds.\n";
}
{
std::vector<notpod> na(sz), nb(sz);
start = std::chrono::high_resolution_clock ::now();
std::copy(na.begin(), na.end(), nb.begin());
end = std::chrono::high_resolution_clock ::now();
std::cout << " NotPOD vector copy took " << (std::chrono::duration<double>(end - start)).count() << " seconds.\n";
}
{
std::vector<Vector3d> a3(sz), b3(sz);
start = std::chrono::high_resolution_clock ::now();
std::copy(a3.begin(), a3.end(), b3.begin());
end = std::chrono::high_resolution_clock ::now();
std::cout << "Vector3d vector copy took " << (std::chrono::duration<double>(end - start)).count() << " seconds.\n";
}
return 0;
}
在我的机器上输出:
POD载体拷贝花了0.135008秒 NotPOD载体拷贝耗时0.35202秒 Vector3d矢量拷贝花了0.35302秒。