gpt4 book ai didi

constness 转换为未定义的行为

转载 作者:太空宇宙 更新时间:2023-11-04 08:07:24 24 4
gpt4 key购买 nike

return cast (==>) 可以让位给未定义的行为吗?代码的想法非常简单,遍历一个侵入式列表(plist)并在找到时返回元素。由于代码只是迭代,它不会更改列表,所以我想将它作为 const 指针传递。

static my_custom_type_t* get_object_by_id(const my_custom_type_t* plist, const char *my_id)
{
const my_custom_type_t* obj = NULL;

for (obj = plist; obj && strncmp(obj->id, my_id, MAX_SIZE); obj = obj->next)
{
; //empty body
}

==> return ((my_custom_type_t*) obj);
}

当函数用于获取对象并将其用作常量时:

const my_custom_type_t* obj = get_object_by_id(intrusive_list, some_id);

当函数用于获取对象并将其用作非常量对象时:

my_custom_type_t* obj = get_object_by_id(intrusive_list, some_id);

最佳答案

C 指定从指针到限定指针的转换,但不是相反,C11 6.3.2.3/2:

For any qualifier q, a pointer to a non-q-qualified type may be converted to a pointer to the q-qualified version of the type; the values stored in the original and converted pointers shall compare equal.

但是,C 允许以下内容,C11 6.3.2.3/7:

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer.

用简单的英语来说,任何指针类型都可以转换为任何其他指针类型并返回。如果指针本身不存在对齐问题,则此类代码没有问题,除非将指针转换为不兼容的类型然后取消引用。合格的类型指针始终是类型指针的兼容类型。

(请注意,这是指指向对象类型的指针 - 函数指针是一种特殊情况。)

所以这是否是 UB 实际上取决于该指针最初指向的位置。在以下情况下调用 UB,C11 6.7.3/6:

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.

如果指针最初指向一个只读位置,您将调用未定义的行为。但如果它指向一个非常量的、分配的变量,那就没问题了。例如,这段代码很好,不会调用未定义的行为:

type t;
type* p = (type*)(const type*)&t1;

否则,正如有人在评论中指出的那样,一些 C 标准库函数将从根本上被破坏,例如 strstr

关于constness 转换为未定义的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41831757/

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