T
Tigera
Greetings,
I've been reading Scott Meyer's book, "Effective C++", and I think
that I've confused myself terribly. I have a class like this:
class Tile
{
private:
Enchantment* m_ench;
Army* m_occupant;
ResourceType m_land_type;
Feature* m_feature;
Gate* m_gate;
public:
Tile();
Army* Occupant() const;
void Occupant(Army* occupant);
Enchantment* TileEnchantment() const;
void TileEnchantment(Enchantment* ench);
ResourceType LandType() const;
void LandType(const ResourceType& land_type);
void SetGate(Gate* new_gate);
Gate* GetGate() const;
void SetFeature(Feature* feature);
Feature* GetFeature() const;
~Tile();
};
Enchantment, Feature, Army, and Gate are all abstract base classes
(ABC's). My question is this: what is the best way to implement
accessors of those fields? According to Items 29 and 30, this sort of
implementation is out because it returns a handle to internal data
that is less accessible than itself:
Gate* Tile::GetGate() const
{
return m_gate;
}
But according to item 31, this is out too because it dereferences a
pointer initialized within a function:
Gate* Tile::GetGate() const
{
return m_gate.copy(); //Where copy returns a pointer to an object
created by new
}
What are my options? Should I return const references instead? I
suppose that I could return std::tr1::shared_ptr's, but I have to
believe that someone had a solution to this problem before that was
invented that didn't involve handles to internal data or memory leaks.
Thanks for your help.
I've been reading Scott Meyer's book, "Effective C++", and I think
that I've confused myself terribly. I have a class like this:
class Tile
{
private:
Enchantment* m_ench;
Army* m_occupant;
ResourceType m_land_type;
Feature* m_feature;
Gate* m_gate;
public:
Tile();
Army* Occupant() const;
void Occupant(Army* occupant);
Enchantment* TileEnchantment() const;
void TileEnchantment(Enchantment* ench);
ResourceType LandType() const;
void LandType(const ResourceType& land_type);
void SetGate(Gate* new_gate);
Gate* GetGate() const;
void SetFeature(Feature* feature);
Feature* GetFeature() const;
~Tile();
};
Enchantment, Feature, Army, and Gate are all abstract base classes
(ABC's). My question is this: what is the best way to implement
accessors of those fields? According to Items 29 and 30, this sort of
implementation is out because it returns a handle to internal data
that is less accessible than itself:
Gate* Tile::GetGate() const
{
return m_gate;
}
But according to item 31, this is out too because it dereferences a
pointer initialized within a function:
Gate* Tile::GetGate() const
{
return m_gate.copy(); //Where copy returns a pointer to an object
created by new
}
What are my options? Should I return const references instead? I
suppose that I could return std::tr1::shared_ptr's, but I have to
believe that someone had a solution to this problem before that was
invented that didn't involve handles to internal data or memory leaks.
Thanks for your help.