为指针分配函数void指针,
double f_dummy(double x) { return x; }
...
void *pv = f_dummy; //compilation error
Run Code Online (Sandbox Code Playgroud)
如本FAQ中所述,这是非法的.然而,答案以声明结束:
如果以上内容似乎适用于特定操作系统上特定版本的特定编译器,请不要给我发电子邮件.我不在乎.这是非法的,期间.
编辑:作为对他人的警告,我确实遇到了这种" 似乎工作 "的行为,通过涉及类模板的继承案例.没有编译器警告,没有意外的运行时行为.
这让我的OCD骨头发痒,让我想知道我一直在做什么,例如,
...
auto l_func = [](double x){ return f_dummy(x); };
void *pv = &l_func;
auto pl = static_cast<decltype(&l_func)>(pv);
cout << (*pl)(5.) << endl;
Run Code Online (Sandbox Code Playgroud)
编译和运行干净(g++ -std=c++11 -Wall),是真正合法的.是吗?
我正在构建一个C++库,它使用许多函数并struct在C库中定义.为了避免将任何代码移植到C++,我将典型的条件预处理添加到C头文件中.例如,
//my_struct.h of the C library
#include <complex.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
double d1,d2,d3;
#ifdef __cplusplus
std::complex<double> z1,z2,z3;
std::complex<double> *pz;
#else
double complex z1,z2,z3;
double complex *pz;
#endif
int i,j,k;
} my_struct;
//Memory allocating + initialization function
my_struct *
alloc_my_struct(double);
#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)
实现alloc_my_struct()是用C编译的.它只是简单地分配内存malloc()并初始化成员my_struct.
现在,当我在C++代码中执行以下操作时,
#include "my_struct.h"
...
my_struct *const ms = alloc_my_struct(2.);
Run Code Online (Sandbox Code Playgroud)
我注意到*ms总是有预期的内存布局,即任何访问,例如ms->z1评估到期望值.考虑到(CMIIW) …
我有以下简单的功能
static inline void
minVec(const double *restrict v, double *restrict vmin, unsigned length){
for (unsigned i = 0; i < length; ++i)
vmin[i] = -v[i];
return;
}
Run Code Online (Sandbox Code Playgroud)
当我以这种方式使用它时编译和运行就好了
double v[] = {1, 2, 3};
minVec(v, v, 3);
Run Code Online (Sandbox Code Playgroud)
我一直认为restrict在这种情况下使用只会告诉编译器循环的每次迭代都独立于其他迭代,因此可以积极地优化循环.这是正确的做法吗?还是我在这里讨论一些实现定义的行为?