WriteBackCMO
WriteBackCMO

Reputation: 619

what happens in memory for move in C++

I am reading c++ primer move section and confused about the move implementation.

Let us say we have one vector that has 4 elements that occupy 4 consecutive memory locations. MEM[0~3]. The capacity of the vector is 4.

Assuming MEM[4] is now not available as it is occupied by another thread or program or due to whatever reason. Is this possible?

Now we need to add another element. Because we must maintain consecutive memory, we can only find another piece of consecutive memory that can host 8 vector entries, for example MEM[5~12]. In this way, we do copy the contents from MEM[0~3] to MEM[5~8] and then add the new element at MEM[9], right?

There is no way we could reuse the old MEM[0~3] and increase capacity while maintaining consecutive addresses.

If it is linked list, i can understand the move. But for array like, I am a bit confused. Please help explain a bit. Thanks.

Upvotes: 2

Views: 409

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118330

This is completely outside the scope of the C++ standard.

There's nothing in the standard that prohibits this optimization. It's certainly possible that a particular C++ implementation determines that the std::vector that already used up its reserve()d capacity can be expanded without allocating larger storage and moving the existing contents of the vector into the larger allocated storage.

If so, then this is a very plausible, and sensible optimization. But nothing in the C++ standard requires this specific optimization either. Given that std::vector's storage expansion algorithm already mandates that the resulting vector insertion must have constant amortized time complexity, it is reasonable to conclude that the additional complexity in tracking memory allocation to such a level of detail may produce only marginal gains, in exchange for larger overhead overall, and might actually prove to incur more overhead, overall.

Upvotes: 4

Related Questions