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

给定一个特征固定大小类型,比如一个Eigen :: Vector3d,为什么类型不是PoD?底层数据是3个双精度数组,不需要非常重要的构造函数或析构函数. 最佳答案 模板方面,很多(取决于版本)在构造函数中继续,尽管在编译时.虽然所有这些都是在编译时进行评估并因此进行了优化,但仍然存在剩余的空构造函数.如果将一个空构造函数添加到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.

点赞