gpt4 book ai didi

c++ - 为什么 Eigen Matrix Library 的具有整数数据的固定大小类型不是 PoD?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:07:48 25 4
gpt4 key购买 nike

给定一个固定大小的 Eigen 类型,比如说 Eigen::Vector3d,为什么这个类型不是 PoD?底层数据是一个包含 3 个 double 的数组,不需要非平凡的构造函数或析构函数。

最佳答案

在模板方面,很多位(取决于版本)在构造函数中进行,尽管是在编译时。虽然所有这些都在编译时进行评估并因此进行了优化,但仍然存在一个空的构造函数。如果您向 POD 类型添加一个空的构造函数,那么在使用 std::copy 时它也不会被 memcpy。试试这个:

#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 vector copy took 0.135008 seconds.
NotPOD vector copy took 0.35202 seconds.
Vector3d vector copy took 0.35302 seconds.

关于c++ - 为什么 Eigen Matrix Library 的具有整数数据的固定大小类型不是 PoD?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42614330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com