今天我偶然发现了一段让我感到恐惧的代码。这些片段在不同的文件中喋喋不休,我尝试在下面的一个简单测试用例中写下它的要点。代码库每天都会使用 FlexeLint 进行例行扫描,但这种结构自 2004 年以来一直存在于代码中。
问题是使用引用传递参数实现的函数被称为使用指针传递参数的函数......由于函数转换。该构造自 2004 年以来一直在 Irix 上运行,现在在移植时它实际上也可以在 Linux/gcc 上运行。
我现在的问题。这是一个可以信任的构造吗?我可以理解编译器构造函数是否实现了引用传递,因为它是一个指针,但它可靠吗?是否存在隐患?
我应该更改fref(..)
使用指针并冒险在此过程中制动任何东西吗?
你怎么看?
编辑
在实际代码中,两者都
fptr(..)
使用fref(..)
相同的struct
- 更改下面的代码以更好地反映这一点。
#include <iostream>
#include <string.h>
using namespace std;
// ----------------------------------------
// This will be passed as a reference in fref(..)
struct string_struct {
char str[256];
};
// ----------------------------------------
// Using pointer here!
void fptr(string_struct *str)
{
cout << "fptr: " << str->str << endl;
}
// ----------------------------------------
// Using reference here!
void fref(string_struct &str)
{
cout << "fref: " << str.str << endl;
}
// ----------------------------------------
// Cast to f(const char*) and call with pointer
void ftest(void (*fin)())
{
string_struct str;
void (*fcall)(void*) = (void(*)(void*))fin;
strcpy(str.str, "Hello!");
fcall(&str);
}
// ----------------------------------------
// Let's go for a test
int main() {
ftest((void (*)())fptr); // test with fptr that's using pointer
ftest((void (*)())fref); // test with fref that's using reference
return 0;
}