std::mem::size_of_val()
on reference of type rather than type itself RS-W1123Calling std::mem::size_of_val()
with a reference to a reference
returns the size of the reference type rather than the value pointed
to by the reference. This can introduce bugs due to size mismatch in
further usage of the calculated value.
struct Foo {
buffer: &[u8],
}
impl Foo {
fn size(&self) -> usize {
// As the `self` argument is already a reference,
// using `&self` yields a double reference `&&Foo`.
// Hence, the return value of `size_of_val()` is the
// size of the reference-type, not the size of `self`.
std::mem::size_of_val(&self)
}
}
struct Foo {
buffer: &[u8],
}
impl Foo {
fn size(&self) -> usize {
// `self` is `&Foo`, hence the function returns
// the size of `Foo` pointed to by `self`.
std::mem::size_of_val(self)
}
}