Search code examples
c++memorygarbage

C++ memory garbaging


I've been teaching myself C++ and someone told me that C++ does not have a garbage collector. Now I'm not sure to what extent this means.

Lets say I have this code :

double multiply (double a, double b) {
    double result = a * b;
    return result;
};
int main (char* args[]) {
    double num1 = 3;
    double num2 = 12;
    double result = multiply(num1, num2);
    return 0;
}

The multiply method contains an internal variable "result". Now is the memory address for the variable "result" still allocated and/or locked? And how about the parameters "a" & "b"?


Solution

  • Standard C++ doesn't have a garbage collector at all.

    But automatic variables ("stack" variables) are cleaned up when their scope ends, calling destructors if/when necessary. (All the variables in your example are automatic.)

    What you have to worry about is dynamic allocations: anything you create via the new operator. Those are not cleaned up automatically - you need to delete them or they will leak. (Or use smart pointers.)