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

问题描述

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

  immutable i = 2; 
immutable s =Hello;

在D 2.0?

解决方案

枚举是用户定义的类型,而不是变量。 枚举e = 2; 是一个
短的东西像这样的枚举:int {e = 2} (即一个匿名
枚举一个成员 e ),请参见。
根据定义,匿名枚举的所有成员将被放置到当前的
范围中。因此, e 是放置在当前作用域中的类型成员,其行为为
,如。另一方面,
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 ashort-hand for something like this enum : int { e = 2 } (i.e. an anonymousenum with one member e), see the documentation.By definition, all members of an anonymous enum are placed into the currentscope. So, e is a type member placed into the current scope, where it behaveslike 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), sinceneither a type nor its members have an address. I.e. you cannot do somethinglike auto ptr = &e; (just like you cannot do auto ptr = &2;). immutablei 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 atcompile time.
  • The compiler can simply replace all appearances of e with 2. For i itusually has to create a memory location (although an optimizing compilermight be able to avoid this sometimes). For this reason, the workload duringcompilation for an enum might be expected to be somewhat lower, and thebinary somewhat smaller.
  • There is a surprising difference for arrays. For enum uint[2] E = [0, 1]; andimmutable uint[2] I = [0, 1]; the access to the enum, e.g. E[0], canbe 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 animmutable array, it is just a normal array lookup to, say, a globalvariable. For the enum however it looks like the array gets created everytime before it gets used, e.g. inside a function for a global enum (don'task me, why, but the compiler really seems to simply replace the appearancewith the value in this case, too). I have never tried but would guess thatthe same applies to enum strings and other non-trivial types.

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

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

08-28 08:07