S.Korai
S.Korai

Reputation: 3

C++ Class array memory reallocation

I'm sorry if this question as already been asked but I have no idea how to word this right. So I'm building an application which needs to be really memory efficient since its on an Arduino Uno (2kbyte sram) and cant load a full array of class objects I need, so I decided to load it in parts. This is basically how I plan to do it:

//declare class object array 
MyClass objects[10];
objects[0] = MyClass(*parameters for initializing*); 
....
....
//Some code with objects
//now changing the objects
objects[0] = MyClass(*parameters for initializing*);

Now my question is will the first objects[0] memory be freed when I change object[0] to the other value? As far as I understand an object is basically a pointer to the fields of the class and when calling a constructor you get a new pointer to a object, so what I'm doing in the code is changing what objects[0] is pointing at but I'm not sure the first pointed at value of objects[0] memory gets freed.

Upvotes: 0

Views: 158

Answers (2)

eerorika
eerorika

Reputation: 238461

Now my question is will the first objects[0] memory be freed when I change object[0] to the other value?

No. Throughout the lifetime of the array, the 10 objects are the same. No objects are ever added or removed. The memory of all the objects (not counting dynamic memory that they may own) is allocated when the lifetime of the array begins, and freed when the lifetime of the array ends.

When you assign to one member of the array, the copy (or move) assignment operator changes the state of the object within the array. The temporary object that was copied from, is destroyed at the end of the assignment.

As far as I understand an object is basically a pointer to the fields of the class

That seems misleading to me. A better analogy is that an object is a block of memory, and the member objects are sub-objects within that memory block. Just like array is a block of memory, and members of the array are sub objects within that memory block.

Your pointer analogy would be appropriate in some languages like Java where non-primitive variables are implicitly pointers. But not in languages like C++, where pointers are explicit, and value semantics are used implicitly.

Upvotes: 1

Quentin
Quentin

Reputation: 63154

As far as I understand an object is basically a pointer to the fields of the class and when calling a constructor you get a new pointer to a object[.]

No, in C++ an object is... well, an actual object. MyClass objects[10] is made of ten MyClasses side-by-side, no pointer involved.

When you write objects[0] = MyClass(/* ... */);, you are constructing a new MyClass, then assigning (copying) it to the first MyClass in the array, then destroying it. Again, no pointer involved.

Upvotes: 5

Related Questions