c++rustmemory-managementmove-semantics

Is this understanding correct: If an object stores everything in itself, copying it and moving it is actually the same thing?


Examples of "objects that stores everything in itself or not" in C++:

using EverythingInMyself1 = int[64];
using EverythingInMyself2 = struct {
    bool flag;
    int head;
    uint8_t data[100];
};

using SomeDataMayNotInMyself1 = std::string;
using SomeDataMayNotInMyself2 = struct {
    bool flag;
    std::unique_ptr<uint8_t[]> data;
};

Examples of "objects that stores everything in itself or not" in Rust:

type EverythingInMyself1 = [i32; 64];
struct EverythingInMyself2 {
    flag: bool,
    head: i32,
    data: [u8; 100]
}

type SomeDataMayNotInMyself1 = String;
struct SomeDataMayNotInMyself2 {
    flag: bool,
    data: Vec<u8>
}

True for all stack-and-heap-based memory allocation languages? Because AFAIK move is actually shallow copy. If an object stores everything in itself, deep copy and shallow copy are the same.


Solution

  • Indeed, if an object holds all its data internally, without referring to external data, duplicating and relocating the object will essentially yield the same result. This occurs because both operations will duplicate all the information contained in the object. In the c++ code you provided, copying and moving EverythingInMyself will produce the same outcome because all data is held within the object itself.