D中的const和不可变之间有什么区别? [英] What is the difference between const and immutable in D?
问题描述
D中 const
和不可变
类型限定词有什么区别?
const
之类的内容无法通过该引用进行更改,但可以通过对以下内容的可变引用进行更改相同的数据。 不可变
不能通过对该数据的任何引用进行突变。因此,如果您有
const C c = foo();
然后,您知道您无法对 c所引用的对象进行突变
到 c
,但是在代码中可能还存在对 c
所引用对象的其他引用,如果它们是可变的,则可以对其进行突变,从而更改 c
的显示。但是如果您有
不可变C c = foo();
然后您知道 c
进行更改。一旦构造了不可变
对象,对其进行突变是非法的,并且除非您通过强制转换来破坏类型系统,否则甚至不可能有可变引用来引用不可变
对象。而且,如果编译器选择将不可变
对象放置到只读存储器中,那么如果您尝试抛弃<$ c $,则实际上会出现段错误等。 c> immutable 并更改对象。对于 const
也是一样,因为 const
引用实际上可以引用不可变
对象。抛弃 const
或 immutable
然后突变然后可变的对象是未定义的行为,并且基本上不应该这样做。 / p>
并且由于不可变的对象永远也不能被另一个引用进行突变,因此读取
不可变来自多个线程的
对象是完全线程安全的。因此,不可变
对象在线程之间隐式共享,而其他未显式标记为 shared
的对象都被视为线程-本地。 不可变
还为编译器提供了比 const
更好的优化机会,因为它保证永不改变,而 const
对象可以通过对同一数据的另一个引用进行更改。
对于值类型,两者之间并没有太大的区别 const
和不可变
(因为您不能对非可变值类型进行可变引用),但是对于引用类型,则存在显着差异。
What is the difference between the const
and immutable
type qualifiers in D?
Something that is const
cannot be mutated via that reference but could be mutated by a mutable reference to the same data. Something that is immutable
can't be mutated by any reference to that data. So, if you have
const C c = foo();
then you know that you cannot mutate the object referred to by c
through c
, but other references to the object referred to by c
may exist in your code, and if they're mutable, they could mutate it and therefore change what c
sees. But if you have
immutable C c = foo();
then you know that it's not possible for the object referred to by c
to change. Once an immutable
object has been constructed, it's illegal for it to be mutated, and unless you subvert the type system via casting, it's not even possible to have a mutable reference to an immutable
object. And since immutable
objects can be put into read-only memory if the compiler chooses to, you could actually get segfaults and the like if you ever tried to cast away immutable
and mutate the object. The same goes for const
, since a const
reference could actually refer to an immutable
object. Casting away either const
or immutable
and then mutating the then mutable object is undefined behavior and should basically never be done.
And since an immutable
object can never be mutated even by another reference, reading an immutable
object from multiple threads is completely thread-safe. So, immutable
objects are implicitly shared across threads, whereas everything else which isn't explicitly marked with shared
is considered thread-local. immutable
also provides better optimization opportunities to the compiler than const
does, because it's guaranteed to never change, whereas a const
object can change through another reference to the same data.
For value types, there isn't really much difference between const
and immutable
(since you can't have mutable references to non-mutable value types), but for reference types, there is a significant difference.
这篇关于D中的const和不可变之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!