Is a destructor called when an object goes out of scope?

前端 未结 5 817
忘掉有多难
忘掉有多难 2020-11-28 23:37

For example:

int main() {
    Foo *leedle = new Foo();

    return 0;
}

class Foo {
private:
    somePointer* bar;

public:
    Foo();
    ~Foo();
};

Foo::         


        
5条回答
  •  不知归路
    2020-11-28 23:55

    there would be a memory leak indeed. The destructor for the object which goes out of scope (the Foo*) gets called, but the one for the pointed-to object (the Foo you allocated) does not.

    Technically speaking, since you are in the main, it is not a memory leak, since you up to when the application is not terminated you can access every allocated variable. With this respect, I cite Alexandrescu (from Modern C++, the chapter about singletons)

    Memory leaks appear when you allocate accumulating data and lose all references to it. This is not the case here: Nothing is accumulating, and we hold knowledge about the allocated memory until the end of the application. Furthermore, all modern

    Of course, this does not imply that you should not call delete, as it would be an extremely bad (and dangerous) practice.

提交回复
热议问题