0

I'm struggling with some concepts of object memory allocation in C++.

Suppose we have a class:

class Foo {
    public:
        Foo();
        ~Foo() {
            delete bar;
        }

    private:
        int* bar = new int(5); //Dynamically allocated with 'new'
}

..and we instantiate this class like so:

int main(void) {
    Foo f1(); //Automatically allocated

    return 0;
}

..what I would like to know is, after the execution of the main() function, is the object destructor called, thus releasing the dynamically allocated memory for the bar variable?

If not, how is it possible to release that memory without being able to call delete f1;? Do we then always need to also dynamically allocate memory for an object, to be able to call delete for that object? For example:

int main(void) {
    Foo f1 = new Foo(5); //Dynamically allocated with 'new'

    delete f1; //Releases 'bar' memory by calling destructor

    return 0;
}

Many thanks for any information!

Callan Heard
  • 727
  • 1
  • 8
  • 18
  • 2
    Yes, destructors for objects with automatic storage duration are called when the containing scope ends. In your case, ~Foo will be run at the end of main(). – Andrew Nov 06 '15 at 13:22
  • First `Foo f1=new Foo(5)` will not compile, you will need a `Foo *f1`. Second, try to use STL Containers or pointer wrappers like `std::unique_ptr` instead of raw pointers. Third, remind the rule of five. And of course, as Andrew said when you exit main, then your object will be destroyed (it's destructor be called). – Werner Henze Nov 06 '15 at 13:29
  • `Foo f1();` This does not actually create an object. Look up most vexing parse. – Neil Kirk Nov 06 '15 at 13:31

0 Answers0