[英]C++ and Swift: How are structs handled in C++ stack frames? Are the complications of struct inheritance why Swift does not support struct inheritance?
At a recent developer meet up the topic of struct
inheritance in Swift (or more precisely the lack of struct
inheritance in Swift) was briefly discussed. 在最近的一次开发者见面的话题struct
继承斯威夫特(或者更准确地说是缺乏struct
斯威夫特继承)进行了展望。 I assumed that the reason why Swift does not support struct
inheritance is because: 我认为Swift不支持struct
继承的原因是因为:
struct
s are value types struct
是值类型 struct
could vary (eg if Lorry
inherits from Vehicle
and Lorry
adds .weightCapacity
then Lorry
will require more space than Vehicle
) 继承意味着struct
的大小可能会有所不同(例如,如果Lorry
继承了Vehicle
和Lorry
.weightCapacity
增加.weightCapacity
那么Lorry
将需要比Vehicle
更多的空间) I assume that it is because of these complications, which presumably would add extra operations to every function call that involves a struct
and thus degrade performance, that Swift does not allow struct
inheritance. 我假设是因为这些复杂性,可能会为涉及struct
每个函数调用添加额外的操作,从而降低性能,Swift不允许struct
继承。 Is this reasoning correct? 这个推理是否正确?
But then I though about C++. 但后来我对C ++这个问题。 C++ does allow struct
inheritance and C++ is very performance focused. C ++确实允许struct
继承,而C ++非常注重性能。 This makes me think that my reasoning for Swift not allowing struct
inheritance is wrong. 这让我觉得我对Swift不允许struct
继承的推理是错误的。 How does C++ achieved struct
inheritance without negatively impacting performance? C ++如何在不对性能产生负面影响的情况下实现struct
继承?
How does C++ achieved struct inheritance without negatively impacting performance? C ++如何在不对性能产生负面影响的情况下实现结构继承?
In C++, the compiler always knows the size of a struct
. 在C ++中,编译器始终知道struct
的大小。 But when a base class is copied by value, the object gets "sliced": only members of the base class are copied, and the new object is not in any way related to the original object's derived class. 但是当通过值复制基类时,对象将被“切片”:仅复制基类的成员,并且新对象与原始对象的派生类没有任何关联。
So if a function wants to do something with a Vehicle
without slicing off its extra identity, it must use a pointer or reference to Vehicle
as the function parameter type or return type. 因此,如果某个函数想要在不切断其额外标识的情况下对Vehicle
执行某些操作,则必须使用指向Vehicle
引用或引用作为函数参数类型或返回类型。 But at that point you no longer have "value types copied between stack frames". 但此时你不再有“在堆栈帧之间复制的值类型”。
Since structs are value types, you are supposed to copy them into the function and back. 由于结构是值类型,因此您应该将它们复制到函数中并返回。 So you could call a non-mutating method with the derived struct, but wouldn't be able to return a derived value from it, so 因此,您可以使用派生结构调用非变异方法,但无法从中返回派生值,因此
struct Vehicle {
var color: Color
mutating func paintWhite() {
self.color = .White
}
}
struct Lorry: Vehicle ...
var lorry = Lorry(color:.Blue)
lorry.paintWhite() // <- wouldn't work, as paintWhite takes inout Vehicle
Without the ability to call mutating methods structs would be much less useful and much more confusing. 如果没有能够调用变异方法的结构,那么结构将变得不那么有用而且更加混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.