Skip to content

Commit

Permalink
Entity: Add placement new
Browse files Browse the repository at this point in the history
For the case where the component may already exist, use a placement new to construct the component again, it would be constructed again, but would not need to go through the allocator.
  • Loading branch information
EmosewaMC committed Sep 30, 2023
1 parent 2562537 commit 7808a52
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
4 changes: 4 additions & 0 deletions dGame/Entity.h
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,10 @@ inline ComponentType* Entity::AddComponent(VaArgs... args) {
// If it doesn't exist, create it and forward the arguments to the constructor
if (!componentToReturn) {
componentToReturn = new ComponentType(this, std::forward<VaArgs>(args)...);
} else {
// In this case the block is already allocated and ready for use
// so we use a placement new to construct the component again as was requested by the caller.
new(componentToReturn) ComponentType(this, std::forward<VaArgs>(args)...);
}

// Finally return the created or already existing component.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ class DestroyableTest : public GameDependenciesTest {
}
};

TEST_F(DestroyableTest, PlacementNewAddComponentTest) {
ASSERT_NE(destroyableComponent, nullptr);
ASSERT_EQ(destroyableComponent->GetArmor(), 7);
baseEntity->AddComponent<DestroyableComponent>();
ASSERT_NE(baseEntity->GetComponent<DestroyableComponent>(), nullptr);
ASSERT_EQ(destroyableComponent->GetArmor(), 0);
}

/**
* Test Construction of a DestroyableComponent
*/
Expand Down

0 comments on commit 7808a52

Please sign in to comment.