gpt4 book ai didi

c++ - 比较 C++ 的空指针值

转载 作者:行者123 更新时间:2023-11-30 00:52:08 25 4
gpt4 key购买 nike

我的实际问题是,当您实际上知道这些值是同一类型时,是否真的可以比较包含在两个空指针中的?例如整数。

void compVoids(void *firstVal, void *secondVal){
if (firstVal < secondVal){
cout << "This will not make any sense as this will compare addresses, not values" << endl;
}
}

其实我需要比较两个void指针值,而在函数外已知类型是int。我不想在函数内部使用 int 比较。所以这对我也不起作用:if (*(int*)firstVal > *(int*)secondVal)有什么建议么?非常感谢您的帮助!

最佳答案

为了比较void*指向的数据,你必须知道类型是什么。如果您知道类型是什么,则不需要 void*。如果你想编写一个可用于多种类型的函数,你可以使用模板:

template<typename T>
bool compare(const T& firstVal, const T& secondVal)
{
if (firstVal < secondVal)
{
// do something
}
return something;
}

为了说明为什么尝试盲目比较 void 指针是不可行的:

bool compare(void* firstVal, void* secondVal)
{
if (*firstVal < *secondVal) // ERROR: cannot dereference a void*
{
// do something
}
return something;
}

因此,您需要知道要比较的大小,这意味着您需要传入一个 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!

这在 C 中是必需的,因为模板不存在。 C++ 有模板,这使得这种类型的函数声明变得不必要和低级(模板允许强制执行类型安全 - void 指针不允许,正如我将在下面展示的那样)。

当你做这样(愚蠢的)事情时,问题就来了:

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.

如您所见,这样做会失去所有类型安全性,并且您必须处理一大堆其他问题。

关于c++ - 比较 C++ 的空指针值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19826715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com