Skip to content

std::mem::size_of_val w/ double-reference #9995

Closed
@crepererum

Description

@crepererum

What it does

Imagine the following code:

struct S {
    field: u32,
    data: Vec<u8>,
}

impl S {
    /// Get size of object including `self`, in bytes.
    pub fn size(&self) -> usize {
        std::mem::size_of_val(self) + (std::mem::size_of::<u8>() * self.data.capacity())
    }
}

Now with a little typo, this is all wrong:

impl S {
    /// Get size of object including `self`, in bytes.
    pub fn size(&self) -> usize {
        // typo is here:      V
        std::mem::size_of_val(&self) + (std::mem::size_of::<u8>() * self.data.capacity())
    }
}

This is because &self will not calculate the size of S but of &S This is most likely NOT what the user wanted, but it's easy to mess up.

This is confusing because the type signature is size_of_val<T>(val: &T) where the the type of the size calculation is NOT a reference but the parameter is (to prevent the value from being moved just for the calculation).

See playground.

Lint Name

size_of_val_on_reference

Category

suspicious

Advantage

Drawbacks

  • there might be good reasons why a users calculates the size of a reference.

Example

fn f(&self) {
    std::mem::size_of_val(&self)
}

Probably meant:

fn f(&self) {
    std::mem::size_of_val(self)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions