fftw3的常量正确性

const correctness of fftw3

本文关键字:正确性 常量 fftw3      更新时间:2023-10-16

摘要

如果外部库的函数需要一个非常量指针(double *),但已知其值保持不变,因此根据常量正确性,我应该传递一个常量指针(const double *),我该怎么办?

情况

我想创建一个函数来计算向量的自动相关性,但不幸的是,fftw3(它是一个C API)似乎不关心const的正确性。我想调用的函数是:

fftw_plan fftw_plan_dft_r2c_1d(int n0,
                                    double *in, fftw_complex *out,
                                    unsigned flags);

我想创建的代码:

vector<double> autocorr(const vector<double>& data)
{
    vector<double> ret(data.size(), 0);
    // prepare other variables
    fftw_plan a = fftw_plan_dft_r2c_1d(size, &data.front(), tmp, FFTW_ESTIMATE);
    // do the rest of the work
    return ret;
}

当然,这不会起作用,因为我的函数的参数是const vector<double>& data,所以我不能调用&data.front()。保持代码常量正确性的最合适的解决方案是什么?

如果您遇到一个C API,它承诺的内容比它在const-正确性方面所表现的内容更多,那么是时候使用const_cast:了

vector<double> autocorr(const vector<double>& data)
{
    vector<double> ret(data.size(), 0);
    // prepare other variables
    fftw_plan a = fftw_plan_dft_r2c_1d(size, const_cast<double*>(&data.front()), tmp, FFTW_ESTIMATE);
    // do the rest of the work
    return ret;
}

还要注意文档中的这句话:

in和out指向变换的输入和输出阵列,它们可能是相同的(产生在位变换)。除非在标志中使用了FFTW_ESTIMATE,否则在规划期间会覆盖这些阵列。

既然您使用的是FFTW_ESTIMATE标志,那么在这种情况下应该没问题。

FFTW开发人员决定为了const而不复制此函数的原因是,在C中,const根本不是什么大事,而FFTW是一个C库。

首先针对库提交错误报告,然后const_cast消除&data.front()的常量,例如const_cast<double*>(&data.front())