I have a constructor which uses an internal Builder object to instantiate a complex object. Five of the members in the data structure are of pointer types. However, using this pattern I am running into problems when the object is destroyed. The following is what my constructor looks like, with member initialization list:
Player::Player(const Builder& builder)
:m_name(builder._name)
,m_description(builder._description)
,m_primaryAttributes(builder._primaryAttributes)
,m_abilityAttributes(builder._abilityAttributes)
,m_armor(builder._armor)
,m_weapon(builder._weapon)
,m_inventory(new ComponentMap())
{}
The client code works well, as expected:
Player* player = Player::Builder()
.name("Dylan")
.description("Super bad-ass hero of the game")
.primaryAttributes(createPrimaryAttributes())
.abilityAttributes(createAbilityAttributes())
.weapon(createWeapon())
.armor(createArmor())
.build();
However, if I omit one of the arguments in the message chain, and then destroy my Player object, bad stuff happens:
Player* player = Player::Builder()
.name("Dylan")
.description("Super bad-ass hero of the game")
.primaryAttributes(createPrimaryAttributes())
.abilityAttributes(createAbilityAttributes())
.armor(createArmor())
.build();
// ...
delete player;
// ...
// cleanMemory() gets called in Player::~Player()
void Player::cleanMemory()
{
if(m_primaryAttributes != NULL )
delete m_primaryAttributes;
if(m_abilityAttributes != NULL )
delete m_abilityAttributes;
if(m_inventory != NULL )
delete m_inventory;
if(m_weapon != NULL) // oops, bad stuff happens here
delete m_weapon;
if(m_armor != NULL)
delete m_armor;
}
Clearly, this happens because the pointer for weapon didn’t get initialized to either NULL or an instance of Weapon object. The constructor also doesn’t appear to allow for a default of NULL (at least from what I can see) in the event that one Builder method is omitted from the chain. For now, the client must either give Weapon a pointer to NULL or an instance of an object.
Is there any possible way to get around this without revising this Builder constructor completely? Or, should this be refactored using another pattern, such as Factory, and just go back to a regular constructor with positional parameter list?
I sample code you referred isn’t very good code base, I would simply suggest below
build pattern:usage:
Or you could just
usage:
As weapon_ptr, armer_ptr are smart pointers, there is no need to call
deletefor the dynamically allocated memory anymore, thuscleanMemory()function can be removed.This is just a simple sample, you could expand the Player’s interfaces to provide ability to build different element after player object is created.