T
tarmat
I've been using code such as the following, whereby I call the
constructor of a class with an object allocated on the heap. The
class is responsible for tidying up the memory.
class Base{};
class A : public Base {};
class B : public Base {};
class MyClass
{
private:
Base* m_pBase;
public:
MyClass(Base* pB):m_pBase(pB){}
~MyClass(){delete m_pBase;}
};
void SomeClass::SomeMethod()
{
//m_pMC is a member variable of type MyClass*
m_pMC = new MyClass(new A());
}
Intuitively, this seems like bad style. I feel that each object should
be responsible for the creation and deletion of objects it uses. Is
this intuition correct?
And, if so, how should I change the design? I can't do something like
void SomeClass::SomeMethod()
{
Base* pB = new A();
m_pMC = new MyClass(pB);
delete pB;
}
because m_pBase must be valid outside the scope of the class method.
How can I improve this design?
Thanks for any help and I hope this made sense!
constructor of a class with an object allocated on the heap. The
class is responsible for tidying up the memory.
class Base{};
class A : public Base {};
class B : public Base {};
class MyClass
{
private:
Base* m_pBase;
public:
MyClass(Base* pB):m_pBase(pB){}
~MyClass(){delete m_pBase;}
};
void SomeClass::SomeMethod()
{
//m_pMC is a member variable of type MyClass*
m_pMC = new MyClass(new A());
}
Intuitively, this seems like bad style. I feel that each object should
be responsible for the creation and deletion of objects it uses. Is
this intuition correct?
And, if so, how should I change the design? I can't do something like
void SomeClass::SomeMethod()
{
Base* pB = new A();
m_pMC = new MyClass(pB);
delete pB;
}
because m_pBase must be valid outside the scope of the class method.
How can I improve this design?
Thanks for any help and I hope this made sense!