Programs use the heap for objects that they dynamically allocate—that is, for objects that the program allocates at run time. The program controls the lifetime of dynamic objects; our code must explicitly destroy such objects when they are no longer needed. Although necessary at times, dynamic memory is notoriously tricky to manage correctly. Dynamic memory is problematic because it is surprisingly hard to ensure that we free memory at the right time.
Either we forget to free the memory—in which case we have a memory leak—or we free the memory when there are still pointers referring to that memory—in which case we have a pointer that refers to memory that is no longer valid.
To make using dynamic memory easier and safer , the new library provides two smart pointer types that manage dynamic objects. A smart pointer acts like a regular pointer with the important exception that it automatically deletes the object to which it points. Therefore, when we create a smart pointer, we must supply additional information—in this case, the type to which the pointer can point. We use a smart pointer in ways that are similar to using a pointer. Dereferenc- ing a smart pointer returns the object to which the pointer points.
And so on. Use with caution; the object to which the returned pointer points will disappear when the smart pointer deletes it. Next, we assign a new value to r. That int is automatically freed as part of assigning q to r. It is up to the implementation whether to use a counter or another data structure to keep track of how many pointers share state.
It does so through another special member function known as a destructor. Analogous to its constructors, each class has a destructor. Just as a constructor controls initial- ization, the destructor controls what happens when objects of that class type are destroyed. Section Uses args to initialize that object. Destructors generally free the resources that an object has allocated.
For ex- ample, the string constructors and other string members allocate memory to hold the characters that compose the string. The string destructor frees that memory. Similarly, several vector operations allocate memory to hold the elements in the vector. The destructor for vector destroys those elements and frees the memory used for the elements. When p is destroyed, its reference count is decremented and checked.
In this case, p is the only object referring to the memory returned by factory. Because p is about to go away, the object to which p points will be destroyed and the memory in which that object resides will be freed. Now when p is destroyed, there will be another user for the memory to which p points.
When a vector is destroyed, the elements in the vector are also destroyed. Some classes allocate resources with a lifetime that is independent of the origi- nal object.
Unlike the containers, we want Blob objects that are copies of one another to share the same elements. That is, when we copy a Blob, the original and the copy should refer to the same underlying elements.
When b2 goes out of scope, those elements must stay around, because b1 is still using them. One common reason to use dynamic memory is to allow multiple ob- jects to share the same state.
The easiest way to implement a new collection type is to use one of the library containers to manage the elements. That way, we can let the library type manage the storage for the elements themselves. Members of an object are destroyed when the object itself is destroyed. For example, assume that b1 and b2 are two Blobs that share the same vector.
If that vector were stored in one of those Blobs—say, b2—then that vector, and therefore its elements, would no longer exist once b2 goes out of scope.
This constructor will take a braced list of initializers. These members forward their work through the data pointer to the underlying vector. These operations must check that an element exists before attempting to access that element.
In addition to an index, check takes a string argument that it will pass to the exception handler. By default, these operations copy, assign, and destroy the data members of the class. Thus, the vector al- located by the StrBlob constructors will be automatically destroyed when the last StrBlob pointing to that vector is destroyed. Exercise If so, add them. Why is it okay to omit that check?
Discuss the pros and cons of this design choice. The new operator allocates memory, and delete frees memory allocated by new. For reasons that will become clear as we describe how these operators work, using these operators to manage memory is considerably more error-prone than using a smart pointer.
As a result, programs that use smart pointers are likely to be easier to write and debug. Until you have read Chapter 13, your classes should allocate dynamic memory only if they use smart pointers to manage that memory. Using new to Dynamically Allocate and Initialize Objects Objects allocated on the free store are unnamed, so new offers no way to name the objects that it allocates. For the same reasons as we usually initialize variables, it is also a good idea to initialize dynamically allocated objects.
The newly allocated object is initialized from the value of obj. Objects of other types must be explicitly ini- tialized. Memory Exhaustion Although modern machines tend to have huge memory capacity, it is always pos- sible that the free store will be exhausted.
Once a program has used all of its avail- able memory, new expressions will fail. A placement new expression lets us pass additional arguments to new. When we pass nothrow to new, we tell new that it must not throw an exception. If this form of new is unable to allocate the requested storage, it will return a null pointer. We return memory through a delete expression. The errors associated with executing delete on pi1 and pd2 are more insidious: In general, compilers cannot tell whether a pointer points to a stat- ically or dynamically allocated object.
Similarly, the compiler cannot tell whether memory addressed by a pointer has already been freed. Most compilers will accept these delete expressions, even though they are in error. The same is not true for memory we manage using built-in pointers. A dynamic object managed through a built-in pointer exists until it is explicitly deleted.
Callers of factory are responsible for freeing this memory when they no longer need the allocated object. That variable is a built-in pointer, not a smart pointer.
Unlike class types, nothing happens when objects of built-in type are destroyed. In particular, when a pointer goes out of scope, nothing happens to the object to which the pointer points. If that pointer points to dynamic memory, that memory is not automatically freed. Dynamic memory managed through built-in pointers rather than smart pointers exists until it is explicitly freed.
Forgetting to delete memory. Testing for memory leaks is difficult because they usually cannot be detected until the application is run for a long enough time to actually exhaust memory.
Using an object after it has been deleted. This error can sometimes be detected by making the pointer null after the delete. Deleting the same memory twice. This error can happen when two pointers address the same dynamically allocated object.
If we subsequently delete the second pointer, then the free store may be corrupted. These kinds of errors are considerably easier to make than they are to find and fix. You can avoid all of these problems by using smart pointers exclusively. The smart pointer will take care of deleting the memory only when there are no remaining smart pointers pointing to that memory. Resetting the Value of a Pointer after a delete. When we delete a pointer, that pointer becomes invalid.
Although the pointer is invalid, on many machines the pointer continues to hold the address of the freed dynamic memory. A dangling pointer is one that refers to memory that once held an object but no longer does so. We can avoid the problems with dangling pointers by deleting the memory associ- ated with a pointer just before the pointer itself goes out of scope.
That way there is no chance to use the pointer after the memory associated with the pointer is freed. If we need to keep the pointer around, we can assign nullptr to the pointer after we use delete. Doing so makes it clear that the pointer points to no object. Provides Only Limited Protection A fundamental problem with dynamic memory is that there can be several point- ers that point to the same memory.
Resetting the pointer we use to delete that memory lets us check that particular pointer but has no effect on any of the other pointers that still point at the freed memory. We delete that memory and set p to nullptr, indicating that the pointer no longer points to an object.
However, resetting p has no effect on q, which became invalid when we deleted the memory to which p and q! Pass that vector to another function that reads the standard input to give values to the elements. Pass the vector to another function to print the values that were read.
Remember to delete the vector at the appropriate time. As described in Table We can bind smart pointers to pointers to other kinds of resources. However, to do so, we must supply our own operation to use in place of delete. If the optional built-in pointer q is passed, p. If d is supplied, will call d to free q otherwise uses delete to free q. The parameter to process is passed by value, so the argument to process is copied into ptr.
Thus, inside process the count is at least 2. When process completes, the reference count of ptr is decremented but cannot go to zero. Therefore, when the local variable ptr is destroyed, the memory to which ptr points will not be deleted. Destroying the temporary decrements the reference count, which goes to zero. The memory to which the temporary points is freed when the temporary is destroyed. But x continues to point to that freed memory; x is now a dangling pointer. Do not sell my personal information.
Close Privacy Overview This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website.
These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience. Necessary Necessary. Kurose, Keith W. Ross Free Download. Tanenbaum, David J. Wetherall Free Download. Bryant, David R.
O'Hallaron Free Download. Pfeiffer, Brent C. Mangus, Dr. Cindy Trowbridge Free Download. Pratt, Mary Z. Last Free Download. Klug, Michael R. Cummings, Charlotte A. Spencer, Michael A. Palladino Free Download. Suchocki, Jennifer Yeh Free Download. Hewitt, John A. Suchocki, Leslie A. Hewitt Free Download. Graham, Donald E. Knuth, Oren Patashnik Free Download. Spradley Late, David W. McCurdy Free Download. Davidson, Walter J. Oleszek, Frances E. Lee Free Download. Judge, John W.
Langdon Free Download. Otie Kilmer Free Download.
0コメント