Memory lifetime

The memory allocated by new will remain valid until you call delete. This means that you may have memory with long lifetimes, and the code may be passed around various functions in your code. Consider this code:

    int *p1 = new int(42);     int *p2 = do_something(p1);     delete p1;     p1 = nullptr;     // what about p2?

This code creates a pointer and initializes the memory it points to and then passes the pointer to a function, which itself returns a pointer. Since the p1 pointer is no longer needed, it is deleted and assigned to nullptr so that it cannot be used again. This code looks fine, but the problem is what do you do with the pointer returned by the function? Imagine that the function simply manipulates the data pointed to ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.