Search code examples
c++pointersdynamic-allocation

what happens if no pointer , gets the factory function pointer?


by mistake , I used a factory function, and did not store the returned pointer anywhere . I am not sure If my question is silly or not , but what happens , if we dynamically , allocate memory in a function , then we return that memory , but do not provide any pointer to store it ? so what happens to the memory ? it means there is no chance at all to delete that? and like this :

Aclass* getAclass()
{
    return new Aclass();
}

int main()
{
    getAclass();
}

Solution

  • There it will remain until the program closes and the operating system reclaims that memory. At least those operating systems that have memory managers or systems that have hardware memory managers.

    It's possible for some languages that have "garbage collectors" to notice that a pointer points to unused memory and will remove that memory itself. You can't obtain the memory without a pointer being returned. If you don't use that pointer, it will be garbage collected assuming the language understands that the memory is no longer in use.