wxObjArray and pointers to elements

If you are using the main C++ distribution of wxWidgets, Feel free to ask any question related to wxWidgets development here. This means questions regarding to C++ and wxWidgets, not compile problems.
Post Reply
Blinkinhek
Experienced Solver
Experienced Solver
Posts: 91
Joined: Tue Aug 16, 2005 10:54 am

wxObjArray and pointers to elements

Post by Blinkinhek »

I have several wxObjArrays in my code. I also use pointers to Items in the arrays (ie &array.Item(index) ). If I Remove an element (ie array.RemoveAt(index) ), do the pointers to the remaining elements stay the same?

Sample code for a simple wxObjArray indicates yes, but I do not know if this is accidental, or by design.

I would like to assume that a sensible array would 'simply' unlink+delete the element to be removed, so retaining the memory addresses of the other elements.
coderrc
Earned some good credits
Earned some good credits
Posts: 141
Joined: Tue Nov 01, 2016 2:46 pm

Re: wxObjArray and pointers to elements

Post by coderrc »

If I understand correctly, you are doing something like

Code: Select all

wxArray<T> objs;
T obj;
objs.AddAt(obj,0);

T* objptr=&objs[0];
in which case the answer is, no. absolutely not.

wxArrays are dynamic, meaning they will resize themselves when needed. "resize" may be a bit misleading. what it really does is alocate a new block of memory, copy itself into that new memory, then free the old memory. Thus after a resize, all pointers to elements in the array will be invalid, even if they still "work" that region of memory can be reallocated by the OS at anytime.
ONEEYEMAN
Part Of The Furniture
Part Of The Furniture
Posts: 7477
Joined: Sat Apr 16, 2005 7:22 am
Location: USA, Ukraine

Re: wxObjArray and pointers to elements

Post by ONEEYEMAN »

Hi,
In addition:

If you remove an element from such an array the memory will still be allocated because the pointer is not yet been deleted.
If you don't need it - delete the pointer instead of removing the object from the array.

Thank you.
Post Reply