constness cast undefined behaviour

后端 未结 2 1290
醉话见心
醉话见心 2021-01-25 19:43

Could the return cast (==>) give place to an undefined behavior? the idea of the code is very simple, iterate through an intrusive list (plist) and return the element if found.

2条回答
  •  星月不相逢
    2021-01-25 20:04

    Could the return cast (==>) give place to an undefined behavior?

    No. casting a (my_custom_type_t*) to (const my_custom_type_t*) does not cause UB.

    Neither does either of the below cause UB

    const my_custom_type_t* plist1;
    const my_custom_type_t* obj1 = get_object_by_id(plist1, "x");
    printf("%d\n", obj1->some_field);
    
    my_custom_type_t* plist2;
    my_custom_type_t* obj2 = get_object_by_id(plist2, "x");
    obj2->some_field = 2;
    

    Yet the following does invoke UB ...

    const my_custom_type_t* plist3;
    my_custom_type_t* obj3 = get_object_by_id(plist3, "x");
    
    // UB
    obj3->some_field = 3;
    

    To avoid this potential, write 2 functions, one being a wrapper of the other.

    static const my_custom_type_t* get_object_by_id_const(
        const my_custom_type_t* plist, const char *my_id) {
      // as above in OP's post
      return obj;
    }
    
    static my_custom_type_t* get_object_by_id_noconst(
        my_custom_type_t* plist, const char *my_id) {
      const my_custom_type_t* obj = get_object_by_id_const(plist, my_id);
      return (my_custom_type_t*) obj;
    }
    

提交回复
热议问题