2

I am new to C++, I was trying to deallocate an object with different ways. Here is my code:

class foo{
public:
    int* bar;

    foo(int N){
        bar = new int[N];
    }

    ~foo(void){
        delete[] bar;
    }
};

int main(int argc, char* argv[]){
    foo* F = new foo(10);
    delete F;
    return 0;
}

This works perfectly, but if I write main like this:

int main(int argc, char* argv[]){
    foo F = foo(10);
    F.~foo();
    return 0;
}

I will end up with an "glibc detected". I guess I should somehow deallocate the "bar" pointer since it was allocated during construction.

Thus my question is how can I deallocate an object like this? Thanks.

Gaohan
  • 31
  • 1
  • 2

1 Answers1

6

For a new to C++ developer, you're wading way too deep.

The line

foo F = foo(10);

does a lot of things. It allocates a temporary new foo object on the stack. Since there's no new, it's NOT in the heap, the lifetime of the temporary object is just that line. It copies the said object to the variable F. Then it destructs the temporary foo.

Your class doesn't define a copy constructor, so C++ copies it by value. By the end of the line, you end up with an object that contains a pointer to a deleted array.

The rest is obvious. The second delete[] errors out.

If you want a foo variable with function scope, do the following instead:

foo F(10);

And also, don't call the destructor explicitly. C++ will call it when the function exits.

In general, every object that manages memory should either define a copy constructor and an assignment operator, or disallow them (by declaring them as private).

In reality, that's rarely needed, since there's already a huge number of classes that manage memory for you, and do so correctly. Since you're learning, it's OK to jump through all the hoops at least once, but in real life, std::vector<int> would gladly store an array of ints for you.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
  • Thank you for detailed explanation, this is super useful! – Gaohan Mar 18 '17 at 19:07
  • "*Your class doesn't define a copy constructor, so C++ copies it by value. By the end of the line, you end up with an object that contains a pointer to a deleted array.*" - See the [Rule of Three](https://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)) to avoid that. – Remy Lebeau Mar 18 '17 at 22:41