Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the Rust compiler 'move' memory?

The Rust standard library provides the Pin<Ptr> struct to prevent the value referenced by the Ptr from being moved. This is useful when dealing with data types which refer to themselves. The compiler may otherwise move data in memory when a semantic move is indicated.

The std::pin documentation provides the following example of a semantic move:

// -snip-

// Create a tracker and store the initial address
let mut tracker = AddrTracker::default();
tracker.check_for_move();

// Here we shadow the variable. This carries a semantic move, and may therefore also
// come with a mechanical memory *move*
let mut tracker = tracker;

// -snip-

This then begs the question, why move data to a new location in the first place? If the compiler never moved data, it would seem like we would not need to have this contract.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Edit: As some have pointed out, moving is necessary when passing data from the stack. This does not, however, explain why Pin<Box<T>> is a common construct, as Box points to data on the heap.

>Solution :

A semantic move may by optimized away such that a physical move is avoided, but such optimizations are not required by the compiler and thus code must be written such that any semantic move could be a physical move.

Some moves cannot be avoided: like assigning a value to or from a different data structure, returning from a function (such that RVO can’t be used), requirements from a specific ABI, etc. With many small types it is preferable (performance-wise) to move them anyway rather than access them via indirection.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading