D语言中的结构和类之间的用法首选项 [英] Usage preference between a struct and a class in D language

查看:82
本文介绍了D语言中的结构和类之间的用法首选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时应该将类型定义为结构或类?

When should I define a type as a struct or as a class?

我知道结构是值类型,而类是引用类型。因此,例如,我想知道是否应该将堆栈定义为结构或类?

I know that struct are value types while classes are reference types. So I wonder, for example, should I define a stack as a struct or a class?

推荐答案

原因#1 选择struct vs class:类具有继承,而结构则没有。如果需要多态性,则必须使用类。

Reason #1 to choose struct vs class: classes have inheritance, structs do not. If you need polymorphism, you must use classes.

原因2:结构通常是值类型(尽管可以将它们设为引用类型)您可以工作)。类始终是引用类型。因此,如果要使用值类型,请选择一个结构。如果要使用引用类型,则最容易使用一个类。

Reason #2: structs are normally value types (though you can make them reference types if you work at it). Classes are always reference types. So, if you want a value type, choose a struct. If you want a reference type, it's easiest to go with a class.

原因#3:如果您的类型很多,数据成员,那么您可能需要引用类型(以避免昂贵的复制),在这种情况下,您可能要选择一个类。

Reason #3: If you have a type with a lot of data members, then you're probably going to want a reference type (to avoid expensive copying), in which case, you're probably going to choose a class.

原因4:如果您想确定性地破坏类型,那么它将需要成为堆栈上的一个结构。 GC堆上的任何内容都没有确定性的销毁,并且GC堆上的东西的析构函数/终结器可能永远不会运行。如果它们是由GC收集的,则将运行其终结器,否则,它们将不会运行。因此,如果希望您的类型在离开作用域时自动销毁,则需要使用一个结构并将其放在堆栈中。

Reason #4: If you want deterministic destruction of your type, then it's going to need to be a struct on the stack. Nothing on the GC heap has deterministic destruction, and the destructiors/finalizers of stuff on the GC heap may never be run. If they're collected by the GC, then their finalizers will be run, but otherwise, they won't. So, if you want your type to automatically be destroyed when it leaves scope, you need to use a struct and put it on the stack.

对于您的特殊情况,容器通常应该是引用类型(每次传递一个元素时复制它们的所有元素会非常昂贵),并且 Stack 是一个容器,所以您要要使用一个类,除非您想让它成为一个ref-counted结构,这无疑是更多的工作。它只是具有保证其析构函数在不再使用时运行的优点。

As for your particular case, containers should normally be reference types (copying all of their elements every time that you pass one around would be insanely expensive), and a Stack is a container, so you're going to want to use a class unless you want to go to the trouble of making it a ref-counted struct, which is decidedly more work. It just has the advantage of guaranteeing that its destructor will run when it's not used anymore.

另一方面,如果创建的容器是一个类,则可能要使其最终化,以便可以内联各种功能(如果该类不是从 Object 和它们不是 Object 所具有的功能),这对于像容器这样的性能绝对重要的东西来说很重要。

On a side note, if you create a container which is a class, you're probably going to want to make it final so that its various functions can be inlined (and won't be virtual if that class doesn't derive from anything other than Object and they're not functions that Object has), which can be important for something like a container where performance can definitely matter.

这篇关于D语言中的结构和类之间的用法首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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