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

前端 未结 5 813
忘掉有多难
忘掉有多难 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-29 00:06

    First note that the code wouldn't compile; new returns a pointer to an object allocated on the heap. You need:

    int main() {
        Foo *leedle = new Foo();
        return 0;
    }
    

    Now, since new allocates the object with dynamic storage instead of automatic, it's not going out of scope at the end of the function. Therefore it's not going to get deleted either, and you have leaked memory.

提交回复
热议问题