fftw3的常量正确性
const correctness of fftw3
摘要
如果外部库的函数需要一个非常量指针(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())
相关文章:
- 代理对象的常量正确性
- std::函数常量正确性未遵循
- C++ 常量正确性/缺少支持常量和非常量实例的类的常量构造函数
- 自定义引用包装器的常量正确性
- 如果我公开常量和非常量 API,我是否破坏了常量正确性?
- 如何强制实施有关指针数据成员的常量正确性
- 如何在C++的多维地图中实现常量正确性
- 将函数赋值给函数指针,常量参数正确性
- C++ 函数参数或声明中的常量正确性
- 结构初始化中的常量正确性
- 常量正确性编译错误到模板函数中的无效转换错误
- 如何在不违反常量正确性的情况下使用 std::lock_guard
- 非平凡变量的常量正确性
- 常量正确性和成员参考
- 常量正确性和shared_ptr,一个设计问题
- 观察者常量正确性
- 如何跨指针保持常量正确性
- 为了速度牺牲常量正确性可以吗
- file read()常量正确性
- C++NULL指针和常量正确性