When are variables removed from memory in C++?

前端 未结 11 1041
梦如初夏
梦如初夏 2020-12-16 06:54

I\'ve been using C++ for a bit now. I\'m just never sure how the memory management works, so here it goes:

I\'m first of all unsure how memory is unallocated in a fu

11条回答
  •  时光说笑
    2020-12-16 07:08

    In C++, any object that you declare in any scope will get deleted when the scoped exits. In the example below, the default constructor is called when you declare the object and the destructor is called on exit, ie, ~MyClass.

    void foo() {
      MyClass object;
      object.makeWonders();
    }
    

    If you declare a pointer in a function, then the pointer itself (the 4 bytes for 32 bit systems) gets reclaimed when the scoped exits, but the memory you might have allocated using operator new or malloc will linger - this is often known as memory leak.

    void foo() {
      MyClass* object = new MyClass;
      object->makeWonders();
      // leaking sizeof(MyClass) bytes.
    }
    

    If you really must allocate an object via new that needs to be deleted when it exits the scope then you should use boost::scoped_ptr like so:

    void foo() {
      boost::scoped_ptr object(new MyClass);
      object->makeWonders();
      // memory allocated by new gets automatically deleted here.
    }
    

提交回复
热议问题