枚举vs不可变D [英] enum vs immutable in D

查看:127
本文介绍了枚举vs不可变D的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 枚举i = 2有什么区别? 
enum s =Hello;

  immutable i = 2; 
immutable s =Hello;

在D 2.0?

解决方案

枚举是用户定义的类型,而不是变量。 枚举e = 2; 是一个
短的东西像这样的枚举:int {e = 2} (即一个匿名
枚举一个成员 e ),请参见文档
根据定义,匿名枚举的所有成员将被放置到当前的
范围中。因此, e 是放置在当前作用域中的类型成员,其行为为
,如 literal 。另一方面,
immutable i = 2; 实际上创建一个变量 i 类型为int



这种差异有以下几个后果:



总结一下:当我使用编译时常量时,通常会采用枚举,除非
这些常量是数组或我需要一个内存位置,其他原因。


What's the difference between

enum i = 2;
enum s = "Hello";

and

immutable i = 2;
immutable s = "Hello";

in D 2.0?

解决方案

An enum is a user-defined type, not a variable. enum e = 2; is a short-hand for something like this enum : int { e = 2 } (i.e. an anonymous enum with one member e), see the documentation. By definition, all members of an anonymous enum are placed into the current scope. So, e is a type member placed into the current scope, where it behaves like a literal. immutable i = 2; on the other hand actually creates a variable i of type int.

This difference has a couple of consequences:

  • enum e will have no memory location and no address (is no lvalue), since neither a type nor its members have an address. I.e. you cannot do something like auto ptr = &e; (just like you cannot do auto ptr = &2;). immutable i on the other hand is a normal variable (just immutable).
  • As discussed by Jonathan, immutable variables can be initialized at compile time or at run-time, whereas a type (with all its members defining the type) must be known at compile time.
  • The compiler can simply replace all appearances of e with 2. For i it usually has to create a memory location (although an optimizing compiler might be able to avoid this sometimes). For this reason, the workload during compilation for an enum might be expected to be somewhat lower, and the binary somewhat smaller.
  • There is a surprising difference for arrays. For enum uint[2] E = [0, 1]; and immutable uint[2] I = [0, 1]; the access to the enum, e.g. E[0], can be orders of magnitude slower than for the immutable array, e.g. I[0], especially as the arrays E and I get bigger. This is so because for an immutable array, it is just a normal array lookup to, say, a global variable. For the enum however it looks like the array gets created every time before it gets used, e.g. inside a function for a global enum (don't ask me, why, but the compiler really seems to simply replace the appearance with the value in this case, too). I have never tried but would guess that the same applies to enum strings and other non-trivial types.

To sum up: when I use compile-time constants, I usually take enum unless those constants are arrays or I need a memory location for some other reason.

这篇关于枚举vs不可变D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆