Keep the entire read path const
The function, loop value, pointer target, and calculated value all state that they will not change.
InventoryComponent.cppcpp
float UInventoryComponent::GetTotalWeight() const
{
float TotalWeight = 0.0f;
for (const FInventoryEntry& Entry : Entries)
{
const UItemDefinition* Definition = Entry.ItemDefinition.Get();
if (Definition == nullptr)
{
continue;
}
const float EntryWeight = Definition->GetWeight() * Entry.Quantity;
TotalWeight += EntryWeight;
}
return TotalWeight;
}- Why
- The compiler catches accidental writes, and callers know the query is safe to use on a const object.
- Costs
- Adding const to an older API can uncover methods that should have been const all along. Fix those declarations instead of casting const away.
- Instead
- Return a copy when the caller needs independent ownership. Return a const reference only when the owner outlives every caller that retains it.

