简体   繁体   English

C ++交换成员数组和关联的指针

[英]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? 然后交换该类,例如在我的标准赋值运算符中使用std::swap(mArray, other.mArray) ,过程中的指针会发生什么?

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? 有任何想法吗?

Even if you change the values stored in mArray , the array is still at the same address. 即使您更改了存储在mArray的值,该数组仍位于同一地址。 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. 不用存储指针,您可以像标准容器一样,并让begin成员将指针/迭代器返回到数据。

int* begin()
{ return mArray; }

And likewise for end() . 同样对于end()

(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: swap不进行指针交换:

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: 之后swap用指针的交换:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM