How do std::array and std::vector differ in extent, storage ownership, object size, moves, allocation, and invalidation?
Show answer and explanation
std::array<T, N> owns exactly N elements inside the array object, and N is part of its type. It does not independently allocate, but that does not mean it is always on the stack: its storage duration and placement follow the object that contains it. Its object size grows with N, and moving it performs element-wise moves. std::vector is a runtime-sized owner of a separate contiguous element sequence; the vector object usually holds a small control representation while allocation and capacity policy belong to the implementation and allocator. A vector move construction can usually transfer that owned allocation cheaply, whereas allocator rules can make move assignment more nuanced. Array element handles remain valid until the array's lifetime ends or the element is replaced. Vector growth can reallocate and invalidate all handles, while other operations have specific invalidation rules. Choose array for fixed extent and value-contained storage, and vector for runtime size and resizable ownership.
std::array<T, N> owns exactly N elements inside the array object, and N is part of its type. It does not independently allocate, but that does not mean it is always on the stack: its storage duration and placement follow the object that contains it. Its object size grows with N, and moving it performs element-wise moves. std::vector is a runtime-sized owner of a separate contiguous element sequence; the vector object usually holds a small control representation while allocation and capacity policy belong to the implementation and allocator. A vector move construction can usually transfer that owned allocation cheaply, whereas allocator rules can make move assignment more nuanced. Array element handles remain valid until the array's lifetime ends or the element is replaced. Vector growth can reallocate and invalidate all handles, while other operations have specific invalidation rules. Choose array for fixed extent and value-contained storage, and vector for runtime size and resizable ownership.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.