1

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:

  1. Is the above example correct? I mean there won't be any leakages, right?
  2. Is it possible somehow to keep normal pointer in ExtClass, and replace 'BaseClass *ptr' with unique_ptr? Or maybe it should be shared_pointer?
rafakob
  • 2,759
  • 2
  • 17
  • 29
  • The code is not smart at all. – cbel Apr 05 '14 at 11:43
  • I suggest you look at `valgrind`. It is a wonderful suite of software that you can run on your code. It will analyze it for you and look for memory leaks etc. While I understand you are doing this here to understand the fundamentals, when your code becomes more complex the chances are good that you leave memory leaks in; so learning to use such tools is an important part of your "no leaky C code" journey. – Floris Apr 05 '14 at 11:44
  • Thanks guys! I know it's not smart at all and I'm just learning how to make it better ;) – rafakob Apr 05 '14 at 11:46
  • Have a look at [this](http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one) – Fredrick Gauss Apr 05 '14 at 11:48
  • Maybe you should read abit about automatic storage duration and RAII – Sebastian Hoffmann Apr 05 '14 at 11:51
  • I was writting an extense answer about (In this order) value semantics, scoped lifetime, resource management (RAII), the rule of three/five, and finally the rule of zero. But has leaded to a mini C++ tutorial. So I show you the points here and suggest you to search over SO and other sites about the topics (In that order). – Manu343726 Apr 05 '14 at 12:20

1 Answers1

0

Okay for the base class, extPtr will be leaked if you exit the function.

To swap a smart pointer with another I believe this is what you want: http://en.cppreference.com/w/cpp/memory/unique_ptr/swap

By the way I don't see any smart-pointerness at all in your code.

Marco A.
  • 41,192
  • 25
  • 117
  • 233