Smart pointer
In computer science, a smart pointer is an abstract data type that simulates a pointer while providing added features, such as automatic memory management or bounds checking. Such features are intended to reduce bugs caused by the misuse of pointers, while retaining efficiency. Smart pointers typically keep track of the memory they point to, and may also be used to manage other resources, such as network connections and file handles. Smart pointers were first popularized in the programming language C++ during the first half of the 1990s as rebuttal to criticisms of C++'s lack of automatic garbage collection.[1][2] Pointer misuse can be a major source of bugs. Smart pointers prevent most situations of memory leaks by making the memory deallocation automatic. More generally, they make object destruction automatic: an object controlled by a smart pointer is automatically destroyed (finalized and then deallocated) when the last (or only) owner of an object is destroyed, for example because the owner is a local variable, and execution leaves the variable's scope. Smart pointers also eliminate dangling pointers by postponing destruction until an object is no longer in use. If a language supports automatic garbage collection (for example, Java or C#), then smart pointers are unneeded for reclaiming and safety aspects of memory management, yet are useful for other purposes, such as cache data structure residence management and resource management of objects such as file handles or network sockets. Several types of smart pointers exist. Some work with reference counting, others by assigning ownership of an object to one pointer. HistoryEven though C++ popularized the concept of smart pointers, especially the reference-counted variety,[3] the immediate predecessor of one of the languages that inspired C++'s design had reference-counted references built into the language. C++ was inspired in part by Simula67.[4] Simula67's ancestor was Simula I. Insofar as Simula I's element is analogous to C++'s pointer without null, and insofar as Simula I's process with a dummy-statement as its activity body is analogous to C++'s struct (which itself is analogous to C. A. R. Hoare's record in then-contemporary 1960s work), Simula I had reference counted elements (i.e., pointer-expressions that house indirection) to processes (i.e., records) no later than September 1965, as shown in the quoted paragraphs below.[5]
Because C++ borrowed Simula's approach to memory allocation—the new keyword when allocating a process/record to obtain a fresh element to that process/record—it is not surprising that C++ eventually resurrected Simula's reference-counted smart-pointer mechanism within element as well. FeaturesIn C++, a smart pointer is implemented as a template class that mimics, by means of operator overloading, the behaviors of a traditional (raw) pointer, (e.g. dereferencing, assignment) while providing additional memory management features. Smart pointers can facilitate intentional programming by expressing, in the type, how the memory of the referent of the pointer will be managed. For example, if a C++ function returns a pointer, there is no way to know whether the caller should delete the memory of the referent when the caller is finished with the information. SomeType* AmbiguousFunction(); // What should be done with the result?
Traditionally, naming conventions have been used to resolve the ambiguity,[6] which is an error-prone, labor-intensive approach. C++11 introduced a way to ensure correct memory management in this case by declaring the function to return a std::unique_ptr<SomeType> ObviousFunction();
The declaration of the function return type as a Creating new objectsTo ease the allocation of a std::shared_ptr<SomeType>
C++11 introduced: auto s = std::make_shared<SomeType>(constructor, parameters, here);
and similarly std::unique_ptr<some_type>
Since C++14 one can use: auto u = std::make_unique<SomeType>(constructor, parameters, here);
It is preferred, in almost all circumstances, to use these facilities over the unique_ptrC++11 introduces A std::unique_ptr<int> p1(new int(5));
std::unique_ptr<int> p2 = p1; // Compile error.
std::unique_ptr<int> p3 = std::move(p1); // Transfers ownership. p3 now owns the memory and p1 is set to nullptr.
p3.reset(); // Deletes the memory.
p1.reset(); // Does nothing.
shared_ptr and weak_ptrC++11 introduces A std::shared_ptr<int> p0(new int(5)); // Valid, allocates 1 integer and initialize it with value 5.
std::shared_ptr<int[]> p1(new int[5]); // Valid, allocates 5 integers.
std::shared_ptr<int[]> p2 = p1; // Both now own the memory.
p1.reset(); // Memory still exists, due to p2.
p2.reset(); // Frees the memory, since no one else owns the memory.
A std::shared_ptr<int> p1 = std::make_shared<int>(5);
std::weak_ptr<int> wp1 {p1}; // p1 owns the memory.
{
std::shared_ptr<int> p2 = wp1.lock(); // Now p1 and p2 own the memory.
// p2 is initialized from a weak pointer, so you have to check if the
// memory still exists!
if (p2) {
DoSomethingWith(p2);
}
}
// p2 is destroyed. Memory is owned by p1.
p1.reset(); // Free the memory.
std::shared_ptr<int> p3 = wp1.lock();
// Memory is gone, so we get an empty shared_ptr.
if (p3) { // code will not execute
ActionThatNeedsALivePointer(p3);
}
Because the implementation of Multiple threads can safely simultaneously access different The referenced object must be protected separately to ensure thread safety.
Other types of smart pointersThere are other types of smart pointers (which are not in the C++ standard) implemented on popular C++ libraries or custom STL, some examples include hazard pointer[12] and intrusive pointer.[13] [14] See also
References
Further reading
External links |
Portal di Ensiklopedia Dunia