Size of a box containing a struct with a trait parameter

半世苍凉 提交于 2021-01-04 06:53:34

问题


I need a struct that contains a trait object and more of itself. Disappointedly the following code does not compile:

trait Foo {}

struct Bar<T: Foo> {
    bars: Vec<Box<Bar<dyn Foo>>>,
    foo: T,
}

I managed to coerce this into compiling by adding the ?Sized bound to T, but I do not understand why this should be the case. I assume this is because all trait objects have the same size, but the size of Bar depends on the size of the concrete type T. If so, how is Bar with an unsized T represented in memory? Specifically what tracks its size on the heap and why can not this mechanism be used in the sized case.


回答1:


The type dyn Foo does not have a size known at compile time. So when you write Bar<dyn Foo>, the compiler won't allow it because (by default) type parameters must be sized. The compiler suggests that you fix this by allowing T to be unsized, which is necessary for T to be dyn Foo.

how is Bar with an unsized T represented in memory?

A struct is allowed to have at most one unsized field. Its data is then laid out in memory with the sized fields first, and then the unsized field last. This restriction means that relative memory addresses of all fields can be known at compile-time. A struct with a ?Sized type parameter can itself be either sized or unsized, depending on the concrete type of its argument. When the struct is unsized, it can't go on the stack so you can only use it from behind a pointer.

There is currently no documentation for this kind of object. It's not exactly a trait object, but it's a pointer to something that may not be sized. As your example shows, this works. But I cannot tell you where the vtable pointer is stored because I don't know, and I'm not sure how to find out.

Specifically what tracks its size on the heap and why can not this mechanism be used in the sized case.

The size of each object doesn't actually change - it's just potentially different per instance. The mechanism can be used "in the Sized case", but you don't have a sized case! Even for a T that is sized, the bars collection will contain boxes of Bar<dyn Foo> which are unsized. That's why you need to T: ?Sized (as opposed to T: !Sized), to say that this type works for T being either sized or unsized.



来源:https://stackoverflow.com/questions/51691288/size-of-a-box-containing-a-struct-with-a-trait-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!