Return value optimization - Unsafe Code Guidelines Reference (original) (raw)

  1. 1. Introduction
  2. 2. Glossary
  3. 3. Data layout
    1. 3.1. Structs and tuples
    2. 3.2. Scalars
    3. 3.3. Enums
    4. 3.4. Unions
    5. 3.5. Pointers
    6. 3.6. Function pointers
    7. 3.7. Arrays and Slices
    8. 3.8. Packed SIMD vectors
  4. 4. Validity
    1. 4.1. Unions
    2. 4.2. Function Pointers
  5. 5. Optimizations
    1. 5.1. Return value optimization

Unsafe Code Guidelines Reference

We should turn

// y unused
let mut x = f();
g(&mut x);
y = x;
// x unused

into

y = f();
g(&mut y);

to avoid a copy.

The potential issue here is g storing the pointer it got as an argument elsewhere.