use*_*977 1 c++ pointers compare void
我实际的问题是,真的有可能比较值当你真正知道这些值是相同类型包含在两个空指针,?例如int.
void compVoids(void *firstVal, void *secondVal){
if (firstVal < secondVal){
cout << "This will not make any sense as this will compare addresses, not values" << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
实际上我需要比较两个void指针值,而在函数外部,已知类型为int.我不想在函数内部使用int的比较.所以这对我也不起作用:有if (*(int*)firstVal > *(int*)secondVal)
什么建议吗?非常感谢您的帮助!
为了比较a指向的数据void*,您必须知道类型是什么.如果您知道类型是什么,则不需要a void*.如果要编写可用于多种类型的函数,可以使用模板:
template<typename T>
bool compare(const T& firstVal, const T& secondVal)
{
if (firstVal < secondVal)
{
// do something
}
return something;
}
Run Code Online (Sandbox Code Playgroud)
为了说明为什么尝试比较void指针盲目是不可行的:
bool compare(void* firstVal, void* secondVal)
{
if (*firstVal < *secondVal) // ERROR: cannot dereference a void*
{
// do something
}
return something;
}
Run Code Online (Sandbox Code Playgroud)
因此,您需要知道要比较的大小,这意味着您需要传入std::size_t参数,或者您需要知道类型(实际上,为了传递std::size_t参数,您必须知道类型):
bool compare(void* firstVal, void* secondVal, std::size_t size)
{
if (0 > memcmp(firstVal, secondVal, size))
{
// do something
}
return something;
}
int a = 5;
int b = 6;
bool test = compare(&a, &b, sizeof(int)); // you know the type!
Run Code Online (Sandbox Code Playgroud)
这在C中是必需的,因为模板不存在.C++有模板,这使得这种类型的函数声明变得不必要和低级(模板允许强制执行类型安全 - 无效指针不会,如下所示).
当你做这样的事情(愚蠢)时会出现问题:
int a = 5;
short b = 6;
bool test = compare(&a, &b, sizeof(int)); // DOH! this will try to compare memory outside the bounds of the size of b
bool test = compare(&a, &b, sizeof(short)); // DOH! This will compare the first part of a with b. Endianess will be an issue.
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,通过这样做,您将失去所有类型的安全性,并且还有许多其他问题需要处理.