Say for example I create a vector with new like this:
std::vector<int>* pointer_to_vector = new std::vector<int>{2, 4, 6, -1};
Will pointer_to_vector remain valid (not dangling) for the rest of the program as long as I don't call delete on the vector? In other words, will the object ever move in memory by itself?
I know the contents of the vector can move in memory but I'm interested in the vector object itself.
And if objects created with new don't move in memory by themselves, and you scale up a program to create lots of them, does new place them close together to minimize cache misses and memory fragmentation, or could they be scattered around distantly?
I am also aware that you can use placement new if you want to control exactly where the object is created in memory but I'm wondering how new handles this automatically.
Are objects created with new guaranteed to stay in the same memory location?
Yes.
Or more specifically, a pointer like your pointer_to_vector
identifies the memory location. And for the lifetime of the object pointed to, that memory location will never become incorrect.
does new place them close together to minimize cache misses and memory fragmentation, or could they be scattered around distantly?
The C++ language makes no guarantee about the locality of multiple calls to new. This behavior is typically decided by a particular operating system, not a language.
However, common implementations of new
typically guarantee that there will always be "some space" between the memory provided by successive calls to new.
If you want several objects to be close together for cache purposes, you should make a single call to new
that allocates all of those objects.