Download

TArray, FStruct and heap

Hi! I am sorry if question is too newbish, I just want to settle this question for myself once and for all, to make sure I never do mistakes in the future.

I have this function:


void MyClass::AddToInventory()
{
FInventoryItem newItemStruct;
newItemStruct.isEquipped = false;
this->equipment.Add(newItemStruct); //-<<<< this->equipment is TArray<FInventoryItem>
}

Now, I am thinking, maybe this code is OK. Maybe, when I add structure like this to tarray, it creates copy and manages its memory.

Or, should I always, no matter what - if I need to keep variable outside function scope in any form - do it like this:


void MyClass::AddToInventory()
{
FInventoryItem * item = static_cast<FInventoryItem *>(FMemory::Malloc(sizeof(FInventoryItem)));
newItemStruct.isEquipped = false;
this->equipment.Add(newItemStruct);
}

If the first scenario is ok (no malloc), then how can I tell, when something creates variable copy and manages its memory? Only by looking at the tarray source code?

If second scenario is ok (with malloc), then should I do it and forget after adding to tarray - i.e. tarray will manage memory for this pointer from now on, and will deallocate later on by itself too?

Thanks!

First example is fine. The struct will be copied into the array.

Second is bad. You (generally) don’t want to do your own malloc…and definitely not without a free.

Using an Emplace would be more efficient.

Hi Ryu,

I think a few high level concepts can help you here.

  1. Separation of Concerns Separation of concerns - Wikipedia

This concept is basically each part of your code should focus its own needs.

Instead of doing all this work in one function

Make the function only worry about its own needs


void MyClass::AddToInventory(FInventoryItem item)
{
  item.UnEquip(); // Telling the item it is not Equipped means this function needs to know less about the item
  this->equipment.Add(item); 
}

In the part of your code that is Calling AddToInventory it can decide what item to create and add to the inventory.

  1. Struct vs Class
    If your item has behavior associated with it its normally better to make it a class. In your case the basic behavior would be something like

void InventoryItem::UnEquip()
{
  this.isEquipped = false;
}

InventoryItem::Equip()
{
  this.isEquipped = true;
  // TODO: track where and who this item is equipped.
}



For a complete working example check out this inventory Tutorial if you have not seen it already

Thank you!! I’ll think it all over carefully now, and hopefully will not need to doubt myself later with the same questions.