Skip to content

vec![Vec::with_capacity(x); n] has unintuitive behaviour. #11537

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
agentsim opened this issue Sep 19, 2023 · 3 comments · Fixed by #11597
Closed

vec![Vec::with_capacity(x); n] has unintuitive behaviour. #11537

agentsim opened this issue Sep 19, 2023 · 3 comments · Fixed by #11597
Labels
A-lint Area: New lints

Comments

@agentsim
Copy link

agentsim commented Sep 19, 2023

What it does

Warns the user when that for n > 1 only the last of the Vec created by the macro will actually have the requested capacity.

Advantage

Alerts the user to some likely unintended behaviour.

@agentsim agentsim added the A-lint Area: New lints label Sep 19, 2023
@Alexendoo
Copy link
Member

std::iter::repeat would run into a similar thing, except none of the vecs would have the desired capacity

@Centri3
Copy link
Member

Centri3 commented Sep 20, 2023

Can you elaborate on why this is the case? That is quite unintuitive ^^

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=b0444384a560393618dd26639192ca49

Basically, why does only the final element have the correct capacity?

@Alexendoo
Copy link
Member

Alexendoo commented Sep 20, 2023

(the unspecialised) vec![foo; n] works by cloning the result of foo, it uses the result directly for the last one since it can avoid an extra clone - https://github.com/rust-lang/rust/blob/62d9034a0d571b78e518727d6cb4b090569e5238/library/alloc/src/vec/mod.rs#L2529-L2555

Cloning a vec doesn't preserve its capacity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants