| Smart Pointer |
Article Index for Smart |
Website Links For Smart |
Information AboutSmart Pointer |
| CATEGORIES ABOUT SMART POINTER | |
| data types | |
|
The use of pointers is a major source of bugs: the constant allocation, deallocation and referencing that must be performed by a program written using pointers makes it very likely that some , the pointed object is destroyed too. Several types of smart pointers exist. Some work with Reference Counting , others assigning ownership of the object to a single pointer. If the language supports automatic garbage collection (for instance, Java), then this use of a smart pointer is unnecessary. In C++ language, smart pointers may be implemented as a template class that mimics, by means of operator overloading, the behaviour of traditional (raw) pointers, (e.g.: dereferencing, assignment) while providing additional memory management algorithms. Smart pointers can facilitate Intentional Programming by expressing the use of a pointer in the type itself. For example, if a C++ function returns a pointer, there is no way to know whether the caller should delete the memory pointed to when the caller is finished with the information.
Traditionally, this has been solved with comments, but this can be error-prone. By returning a C++ Auto_ptr ,
auto_ptr the function makes explicit that the caller will take ownership of the result, and further more, that if the caller does nothing, no memory will be leaked. Similarly, if the intention is to return a pointer to an object managed elsewhere, the function could return by reference: some_type& obvious_function2(); EXAMPLE Let SmartPointer void test_smartpointers() { //first, we create two objects and we keep raw pointers to them //since these pointers are not smart, they will not affect the object lifecycle
//then we declare two smart pointers and we assign them with the objects //both obj_1 and obj_2 will have counter==1 SmartPointer SEE ALSO
EXTERNAL LINKS
|
|
|