tomatoBisque
tomatoBisque

Reputation: 153

C++ Swapping Member Arrays and Associated Pointers

If I have a class containing a member array with pointers at each end, for example,

int mArray[5];
int *mStart = mArray;
int *mEnd = mArray + 5;

and I swap that class, say in my standard assignment operator using std::swap(mArray, other.mArray), what happens to the pointers in the process?

This is a very contrived example, but in my program, if I swap just the array, the assignment operator works as intended, and if I try to swap all three member variables, it crashes. Any ideas?

Upvotes: 0

Views: 152

Answers (2)

molbdnilo
molbdnilo

Reputation: 66371

(Assuming these are not actually static members, but that you mean that they're not dynamically allocated.)

When you swap the arrays, the arrays don't move; only their contents are swapped.
(Arrays are not pointers.)

The reason it doesn't work if you swap the pointers is that the pointers then point into the array member of their "original" object.
If you don't swap them, they keep pointing into the array they were created from.

Ilustrating example:

Starting point:

Object A: mArray starts at 0x1000; mStart is 0x1000; mEnd is 0x1014
Object B: mArray starts at 0x2000; mStart is 0x2000; mEnd is 0x2014

After swap without pointer-swapping:

Object A: mArray starts at 0x1000; mStart is 0x1000; mEnd is 0x1014
Object B: mArray starts at 0x2000; mStart is 0x2000; mEnd is 0x2014

After swap with pointer-swapping:

Object A: mArray starts at 0x1000; mStart is 0x2000; mEnd is 0x2014
Object B: mArray starts at 0x2000; mStart is 0x1000; mEnd is 0x1014

Upvotes: 1

Bo Persson
Bo Persson

Reputation: 92271

Even if you change the values stored in mArray, the array is still at the same address. So the pointers continue to be correct.

If you swap the pointer values with another object, the pointers in one object will then point to the array of the other object. Not going to work very well!

Instead of storing a pointer, you could do like the standard containers and have a begin member returning a pointer/iterator to the data.

int* begin()
{ return mArray; }

And likewise for end().

Upvotes: 1

Related Questions