Why sizeof of a struct is unsafe

前端 未结 2 1243
礼貌的吻别
礼貌的吻别 2021-02-19 23:44

The MSDN clearly states

For all other types, including structs, the sizeof operator can only be used in unsafe code blocks.

The C#

2条回答
  •  没有蜡笔的小新
    2021-02-20 00:18

    I would like to know why using sizeof in this context is considered unsafe.

    Matthew Watson's comment hits the nail on the head. What are you going to do with that information in safe code? It's not useful for anything(*). It doesn't tell you how many unmanaged bytes you need to allocate to marshal; that's Marshal.SizeOf. It's only useful for pointer arithmetic, so why should it be in the safe subset?


    (*) OK to be fair there are a few odd corner case usages for a safe sizeof that can take structs that contain managed types. Suppose for example you have a generic collection class that is going to allocate a bunch of arrays and would like to ensure that those arrays are not moved into the large object heap; if you could take the size of a struct that contained managed objects then you could write this code very easily, and it would not need any pointer arithmetic. But the fact remains that sizeof was designed specifically for pointer arithmetic, and not so that you could do an end-run around the garbage collection heuristics for arrays.

提交回复
热议问题