问题
I know a contiguous block of memory is allocated for an array.
My first question is when the array element is an object rather than a built-in type, what gets stored in the contiguous memory reserved for the array? Pointer for the object or the actual data for the object? My guess is pointers are stored in the array and the actual objects are stored randomly in the heap. Am I correct?
My second question is now we want to reserve a specified memory(e.g., shared memory) for an array of objects. What is the best way to achieve this? Should I serialise the actual objects in the specified memory one by one and use relative pointers(e.g., indices) to access each of them?
回答1:
Not at all correct. An array T[N] contains N elements of type T, directly stored in contiguous memory. The array occupies N * sizeof(T) bytes of memory.
Conversely, to answer your second question, any run of N * sizeof(T) bytes of memory can be used to hold N elements of type T (subject to some alignment constraints perhaps).
回答2:
No, the objects are stored unless you have an array of pointers. Generally, c++ does what you ask for and takes no liberties.
Storing the objects in shared memory depends on the nature of your objects, you basically better stick to plain data, I think.
回答3:
Nope, the objects themselves are stored. The name of the array just gives you a pointer to the first element, which you can then use pointer arithmetic on to traverse the array.
回答4:
I would say I depends on kind of source code of an object.
class an_my_object_a {
private:
something_t something;
something_else_t something_else;
third_field_t third_field;
public:
//there are some methods
}
class an_my_object_b {
private:
an_my_object_a * d;
public:
//there are some methods
}
The array of an_my_object_a may store all its data in continuous memory. The array of an_my_object_b is practically an array of pointers.
来源:https://stackoverflow.com/questions/8297993/how-is-an-array-of-objects-stored-in-memory