【问题标题】:Why should I use 1bit bitfields instead of bools?为什么我应该使用 1 位位域而不是书籍?
【发布时间】:2014-12-15 16:44:52
【问题描述】:
UCLASS(abstract, config=Game, BlueprintType, hidecategories=("Pawn|Character|InternalEvents"))
class ENGINE_API ACharacter : public APawn
{
    GENERATED_UCLASS_BODY() 
...
    UPROPERTY(Transient)
    uint32 bClientWasFalling:1; 

    /** If server disagrees with root motion track position, client has to resimulate root motion from last AckedMove. */
    UPROPERTY(Transient)
    uint32 bClientResimulateRootMotion:1;

    /** Disable simulated gravity (set when character encroaches geometry on client, to keep him from falling through floors) */
    UPROPERTY()
    uint32 bSimGravityDisabled:1;

    /** 
     * Jump key Held Time.
     * This is the time that the player has held the jump key, in seconds.
     */
    UPROPERTY(Transient, BlueprintReadOnly, VisibleInstanceOnly, Category=Character)
    float JumpKeyHoldTime;

上面的代码来自 UE4。他们似乎使用 uint32 一位位域而不是布尔值。他们为什么要这样做?

【问题讨论】:

  • 我想这是为了节省空间。
  • bool 不使用一位,所以如果他们打包超过 4 个变量,他们会获得一些空间。
  • UE4 是一个现代引擎。节省内存对现代系统至关重要吗?

标签: c++ unreal-engine4


【解决方案1】:

独立的bool 至少有一个字节长。处理器不能处理更小的单元。但是,我们都知道一个字节可以容纳 8 位/布尔值,所以如果您有一个具有多个布尔值的数据结构,则每个字节都不需要一个字节。他们可以共享一个字节。如果你有很多这样的结构,它可能会节省一些内存。

【讨论】:

  • 但是访问位域通常比较慢,并且不能以原子方式完成(例如,对于多线程应用程序)
  • 确实如此。我猜开发人员发现这段代码中的好处比坏处更有帮助,也许其他人会在另一段代码中对它进行不同的加权。
  • @BasileStarynkevitch 在某些架构上可以实现原子位域访问。 amd64 可能不支持这个,但armv6 支持原子读取。
猜你喜欢
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 2011-05-28
  • 2018-05-10
  • 2014-03-12
  • 2012-12-13
相关资源
最近更新 更多