C#中的双按位NOT(~~)
作者:互联网
我一直在阅读ThreadLocal< T>实现,并且不太了解将int id转换为私有ind字段(m_idComplement)之前将int id反转,然后在几乎所使用的每个表达式中再次将其反转的原理.除了适用于JavaScript的this case,我不能找到任何有关为什么在C#中使用双重取反的信息?
在第240行,它确实分配了0,而没有取反,但是它本可以分配为-1,然后丢弃所有其他不必要的值,不是吗?
https://dl.dropboxusercontent.com/u/65419748/ThreadLocal.cs
https://i.imgur.com/3z3F64V.png
解决方法:
ThreadLocal.cs的reference source包含针对此字段的以下注释:
Slot ID of this ThreadLocal<> instance. We store a bitwise complement of the ID (that is ~ID), which allows us to distinguish between the case when ID is 0 and an incompletely initialized object, either due to a thread abort in the constructor, or possibly due to a memory model issue in user code.
他们实际上是将ID的默认,未初始化值从0切换为-1,如果将其直接作为int字段存储,则为0.
标签:bit-manipulation,c 来源: https://codeday.me/bug/20191121/2052807.html