I give the following example to illustrate my question. Suppose Abc
is a class that will use another class (Def
). Assume Def
is a large class with many class members (expensive for copying), it make more sense to let the pointer to a Def object be part of Abc class. Then when implementing Abc
class function do1
, it can refers to Def object via its pointer pDef
.
class Abc
{
public:
Abc(Def &def)
{
pDef = &def;
}
~Abc()
{
}
void do1();
private:
Def *pDef;
}
However, if I implement class Abc in this way, I will have the risk that the Def
pointer might be invalid. Any ideas on improving this class design? One idea I have is to use share pointer:
class Abc
{
public:
Abc(boost::shared_ptr<Def> def)
{
pDef = def;
}
~Abc()
{
}
void do1();
private:
boost::shared_ptr<Def> pDef;
}
EDIT: I want to make it clear that my main purpose is to avoid the expensive copy operation when constructing class Abc
. For me using the shared pointer and James Adkison's solution (accepted answer) can both solve the problem. But the effect on the expensive Def
object may be different. Using shared pointer will keep many copies of the object while using James Adkison's solution will only keep one copy of Def
object.