When is an integer<->pointer cast actually correct?

后端 未结 15 2641
北荒
北荒 2020-12-13 07:48

The common folklore says that:

  • The type system exists for a reason. Integers and pointers are distinct types, casting between them is a malpractice in the m

15条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 08:28

    under x64, on can use the upper bits of pointers for tagging (as only 47 bits are used for the actual pointer). this is great for things like run time code generation (LuaJIT uses this technique, which is an ancient technique, according to the comments), to do this tagging and tag checking you either need a cast or a union, which basically amount to the same thing.

    casting of pointers to integers can also be very helpful in memory management systems that make use of binning, ie: one would be able to easily find the bin/page for an address via some math, an example from a lockless allocator I wrote a while back:

    inline Page* GetPage(void* pMemory)
    {
        return &pPages[((UINT_PTR)pMemory - (UINT_PTR)pReserve) >> nPageShift];
    }
    

提交回复
热议问题