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 by the pointer:

    int *do_something(int *p) 
{
*p *= 10;
return p;
}

In effect, calling do_something creates a copy of a pointer, but not a copy of what it points to. This means that when the p1 pointer is deleted, the memory it points to is no longer available, and so the pointer p2 points to the invalid memory.

This problem can be addressed using a mechanism called Resource Acquisition Is Initialization (RAII), which means using the features of C++ objects to manage resources. RAII in C++ needs classes and in particular, copy constructors and destructors. A smart pointer class can be used to manage a pointer so that when it is copied, the memory it points to is also copied. A destructor is a function that is called automatically when the object goes out of scope and so a smart pointer can use this to free memory. Smart pointers and destructors will be covered in Chapter 4, Classes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset