I'm learning how to use properly pointers and 'smart pointers' to prevent memory leakages. Here's a fragment of pseudo-code that I'm analyzing. [ ClassA and ClassB inherit BaseClass; ExtClass is just some external class (not related with BaseClass ]
main(){
ExtClass *extPtr = new ExtClass();
BaseClass *ptr = new ClassA();
extPtr->setPtr(ptr);
extPtr->fun();
...
if(change_object()) {
delete ptr;
ptr = new ClassB();
extPtr->setPtr(ptr);
extPtr->fun();
}
}
-------------------------------------
ExtClass {
private:
BaseClass *m_ptr;
public:
~ExtClass() { delete m_ptr; }
void ExtClass::fun(){
m_ptr->do_some_stuff();
}
void ExtClass::setPtr(BaseClass *ptr){
m_ptr = ptr;
}
}
Questions:
- Is the above example correct? I mean there won't be any leakages, right?
- Is it possible somehow to keep normal pointer in ExtClass, and replace 'BaseClass *ptr' with unique_ptr? Or maybe it should be shared_pointer?