I run into some issue with Pointers and looking for help.
So for demonstration: Created a new project, then a new c++ class, from that a Blueprint and placed in the scene.
.h is unmodified, Cpp as quoted.
So my issue is that, I created pointer to the 0 place in the array, then a swap 0,1 position.
Before the swap I got back the original value as expected.
After the swap the same pointer reads back the value from array position 0, but my intention is to get back the original value after the operation.
With other operation like reserve, a got a garbled value from that memory location.
So my question is ow can a create a “dynamic” pointer so it follows the original value?!
Is such a thing even possible?
void AActor_General_Code_Tester::BeginPlay()
{
Super::BeginPlay();
TArray<int> TestArray;
TestArray.Add(123456789);
TestArray.Add(464815);
int* Pointer = &TestArray[0];
UE_LOG(LogTemp, Warning, TEXT("Test value before resize: %d"), *Pointer); //Got back the original value (123456789)
TestArray.Swap(0, 1);
UE_LOG(LogTemp, Warning, TEXT("Test value after resize: %d"), *Pointer); //Got back the value from the array place 0 but memory place Pointer (464815)
}
Swap function only swaps the values of the elements, not its memory location. You can store an int pointer instead on your array BUT this is prone to memory leak and unnecessary heap allocation. Not sure about your real use case for this but I might consider rethinking how to handle the logic better instead. In any case, just to show the difference of the change I mentioned, here’s its code:
TArray<int*> TestArray;
TestArray.Add(new int(123456789));
TestArray.Add(new int(464815));
int* Pointer = TestArray[0];
UE_LOG(LogTemp, Warning, TEXT("Test value before swap: %d"), *Pointer);
TestArray.Swap(0, 1);
UE_LOG(LogTemp, Warning, TEXT("Test value after swap: %d"), *Pointer);
In my case the TArray is heap sorted and unknown number of element added(A* algorithm) to it. At a point I reference to an element but after sorting I need to keep a reference to the same element, but the sorting changes the orders and the pointer is technically still valid but pointing to the wrong element/value.
I could run a Find, but due the size of the array and number of cycles it causes poor performance, also maintaining a reference is much more elegant.
I don’t think what you are looking for is possible without a rework of the TArray class.
I tried some things even with two arrays and a fancy wrapper struct with overrides for copy/move operators, so that it can track its own index into the array. But in the end they don’t matter because TArray::Swap swaps the memory directly and doesn’t call any of those operators on the struct, so it’s impossible for it to be aware of its index change.
If you don’t use TArray Sort/Swap and make your own functions to do the sorting and swapping then it might be possible.