DON BOX: Smart Pointers: What, Why, Which?

zhaozj2021-02-16  62

What Are The Objects That Look and Feel Like Pointers, But Are Smarter. What Does this mean?

To look and feel like pointers, smart pointers need to have the same interface that pointers do: they need to support pointer operations like dereferencing (operator *) and indirection (operator ->) An object that looks and feels like something else is called. .

To be smarter than regular pointers, smart pointers need to do things that regular pointers do not What could these things be Probably the most common bugs in C (and C) are related to pointers and memory management:.? Dangling pointers, memory leaks ALOCATION FAILES AND OTHER JOYS. HAVING A Smart Pointer Take Care of these Things CAN Save a Lot of Aspirin ...

The simplest example of a smart pointer is auto_ptr, which is included in the standard C library. You can find it in the header , or take a look at Scott Meyers' auto_ptr implementation. Here is part of auto_ptr's implementation, to illustrate What it does:

Template Class Auto_PTR

{

T * PTR;

PUBLIC:

Explicit auto_ptr (t * p = 0): PTR (P) {}

~ Auto_PTR () {Delete Ptr;}

T & operator * () {return * ptr;}

T * Operator -> () {Return PTR;}

// ...

}

As you can see, auto_ptr is a simple wrapper around a regular pointer It forwards all meaningful operations to this pointer (dereferencing and indirection) Its smartness in the destructor:.. The destructor takes care of deleting the pointer.

For the user of auto_ptr, this means That Instead of Writing: Void foo ()

{

Myclass * p (new myclass);

P-> DOSMETHING ();

Delete P;

}

You Can Write:

Void foo ()

{

Auto_ptr p (new myclass);

P-> DOSMETHING ();

}

And Trust P to Cleanup After Itself.

What does this buy you? See the next section.

Why Would I Use The THEM? OBVIOSLY, DIFFERENT SMART POINTERS OFFERENT Reasons for Use. Here Area Some Common Reasons for Using Smart Pointers In C .

Why: Less Bugs

Automatic cleanup As the code above illustrates, using smart pointers that clean after themselves can save a few lines of code The importance here is not so much in the keystrokes saved, but in reducing the probability for bugs:.. You do not need to Remember to free the pointer, and solace you will forget About it.

Automatic Initialization. Another Nice Thing is this Auto_ptr To Null, Since The Default Construction.

Dangling Points. A Common Pitfall of Regular Pointers Is The Dangling Pointer: a Pointer That Points To An Object That Is Already Deleted. The Following Code Illustrates this situation:

Myclass * p (new myclass);

Myclass * q = p;

Delete P;

P-> DOSMETHING (); // Watch out! P is now dangling!

P = null; // p is no longer dangling

Q-> DOSMETHING (); // ooch! q is stock dangling!

For auto_ptr, this is solved by Setting ITS Pointer to Null When IT IS Copie:

Template

Auto_PTR & Auto_Ptr :: Operator = (Auto_Ptr & RHS)

{

IF (this! = & r HS) {

Delete PTR;

PTR = rhs.ptr;

RHS.PTR = NULL;

}

Return * this;

}

Other smart pointers may do ivher things when copy copied. Here are things the statement = p, where p and q Are Smart Pointers:

Create a new copy of the object pointed by p, and have q point to this copy This strategy is implemented in copied_ptr.h Ownership transfer:.. Let both p and q point to the same object, but transfer the responsibility for cleaning up ( "ownership") from p to q This strategy is implemented in owned_ptr.h Reference counting:... Maintain a count of the smart pointers that point to the same object, and delete the object when this count becomes zero So the statement q = . p causes the count of the object pointed by p to increase by one This strategy is implemented in counted_ptr.h Scott Meyers offers another reference counting implementation in his book More Effective C Reference linking:.. The same as reference counting, only instead of . a count, maintain a circular doubly linked list of all smart pointers that point to the same object This strategy is implemented in linked_ptr.h Copy on write:. Use reference counting or linking as long as the pointed object is not modified When it. IS ABO ut to be modified, copy it and modify the copy. This strategy is implemented in cow_ptr.h. All these techniques help in the battle against dangling pointers. Each has each own benefits and liabilities. The

Which Section of this Article Discusses The Suitability of Different Smart Pointers for Various Situations.

Why: Exception Safetylet's Take Another Look At this Simple Example:

Void foo ()

{

Myclass * p (new myclass);

P-> DOSMETHING ();

Delete P;

}

What happens if DoSomething () throws an exception? All the lines after it will not get executed and p will never get deleted! If we're lucky, this leads only to memory leaks. However, MyClass may free some other resources in its destructor (file handles, threads, transactions, COM references, mutexes) and so not calling it my cause severe resource locks.If we use a smart pointer, however, p will be cleaned up whenever it gets out of scope, whether it was during the Normal path of execution or during the stack unwinding caused by throwing an exception.

But is not it possible to write exception safe code with regular pointers Sure, but it is so painful that I doubt anyone actually does this when there is an alternative Here is what you would do in this simple case?.:

Void foo ()

{

Myclass * p;

Try {

P = new myclass;

P-> DOSMETHING ();

Delete P;

}

Catch (...) {

Delete P;

Throw;

}

}

Now Imagine What Would Happen if We Had Some IF's and for's in there ...

Why: Garbage collectionSince C does not provide automatic garbage collection like some other languages, smart pointers can be used for that purpose The simplest garbage collection scheme is reference counting or reference linking, but it is quite possible to implement more sophisticated garbage collection schemes with. Smart pointers. for more information see

THE GARBAGE Collection FAQ.

Why: EfficiencySmart Pointers Can Be Used to Make More Efficient Use of Available Memory and to Shorten Allocation and deallocation time.

A common strategy for using memory more efficiently is copy on write (COW). This means that the same object is shared by many COW pointers as long as it is only read and not modified. When some part of the program tries to modify the object ( "write"), the COW pointer creates a new copy of the object and modifies this copy instead of the original object. The standard string class is commonly implemented using COW semantics (see the header) .string s ( "Hello ");

String t = s; // t And s point to the Same buffer of character

T = "there!"; // a new buffer is allocated for t before

// appending "there!", SO S is unchanged.

Optimized allocation schemes are possible when you can make some assumptions about the objects to be allocated or the operating environment. For example, you may know that all the objects will have the same size, or that they will all live in a single thread. Although it is possible to implement optimized allocation schemes using class-specific new and delete operators, smart pointers give you the freedom to choose whether to use the optimized scheme for each object, instead of having the scheme set for all objects of a class. It is . t.....................

Why: STL Containersthe C Standard Library Includes a Set of Containers and Algorithms Known As The Standard Template Library (STL).

STL IS Designed to BE

Generic (can be used with any kind of object) and

efficient (does not incur time overhead compared to alternatives). To achieve these two design goals, STL containers store their objects by value. This means that if you have an STL container that stores objects of class Base, it can not store of objects of classes Derived from base.class base {/*...*/};

Class Derived: Public Base {/*.../};

Base B;

Derived D;

Vector v;

v.push_back (b); // ok

v.push_back (d); // error

What can you do if you need a collection of objects from Different Classes? The Simplest Solution Is To Have A Collection of Pointers:

Vector v;

v.push_back (new base); // ok

v.push_back (new derived); // ok TOO

// cleanup:

For (Vector :: item i = v.begin (); i! = v.end (); i)

Delete * i;

....................... ..

Smart Pointers Are A Possible Solution, As Illustrate Below. (An Alternative Solution IS A Smart Container, Like The One Implement in Pointainer.h.)

Vector >.

v.push_back (new base); // ok

v.push_back (new derived); // ok TOO

// cleanup is automatic

.

Note:. STL containers may copy and delete their elements behind the scenes (for example, when they resize themselves) Therefore, all copies of an element must be equivalent, or the wrong copy may be the one to survive all this copying and deleting. This means that some smart pointers can not be used within STL containers, specifically the standard auto_ptr and any ownership-transferring pointer. For more info about this issue, see C Guru of the Week # 25.Which one should I use? Are you confused enough Well, this Summary Should Help.

Which: Local variablesThe standard auto_ptr is the simplest smart pointer, and it is also, well, standard If there are no special requirements, you should use it For local variables, it is usually the right choice...

Which: Class membersAlthough you can use auto_ptr as a class member (and save yourself the trouble of freeing objects in the destructor), copying one object to another will nullify the pointer, as illustrated Below.

Class myclass

{

Auto_ptr P;

// ...

}

Myclass x;

// do some meaningful things with x

Myclass y = x; // x.p now Has a null pointer

.

Note that using a reference counted or reference linked pointer means that if y changes the member, this change will also affect x! Therefore, if you want to save memory, you should use a COW pointer and not a simple reference counted / linked pointer.

Which: STL Containersas Explained Above, USING GARBAGE-Collected Pointers with Stl Containers Lets You Store Objects from Different Classes in The Same Container.

It is important to consider the characteristics of the specific garbage collection scheme used. Specifically, reference counting / linking can leak in the case of circular references (ie, when the pointed object itself contains a counted pointer, which points to an object that contains the original counted pointer). Its advantage over other schemes is that it is both simple to implement and deterministic. The deterministic behavior may be important in some real time systems, where you can not allow the system to suddenly wait while the garbage collector performs its housekeeping duties .Generally speaking, there are two ways to implement reference counting: intrusive and non-intrusive intrusive means that the pointed object itself contains the count Therefore, you can not use intrusive reference counting with 3-rd party classes that do not already have this.. Feature. You Class from the 3-rd Party Class and Add The Count To It. Non-Intrusive Reference Counting R Equires an allocation of a count for each counted Object. The counted_ptr.h IS An Example of Non-Intrusive Reference Counting.

Reference linking does not require any changes to be made to the pointed objects, nor does it require any additional allocations A reference linked pointer takes a little more space than a reference counted pointer -. Just enough to store one or two more pointers.

Both Reference Counting and Reference Linking Require Using Locks if The Pointers Area Used by More Than Thread of Execution.

Which: EXPLICIT OWNERSHIP TRANSFER

Sometimes, you want to receive a pointer as a function argument, but keep the ownership of this pointer (ie the control over its lifetime) to yourself. One way to do this is to use consistent naming-conventions for such cases. Taligent's Guide to Designing Programs recommends using "adopt" to mark that a function adopts ownership of a pointer.Using an owned pointer as the function argument is an explicit statement that the function is taking ownership of the pointer.

Which: Big Objects

If you have objects that take a lot of space, you can save some of this space by using COW pointers. This way, an object will be copied only when necessary, and shared otherwise. The sharing is implemented using some garbage collection scheme, like Reference counting or lineing.

Which: Summary

For this: Use that: Local variablesauto_ptrClass membersCopied pointerSTL ContainersGarbage collected pointer (e.g. reference counting / linking) Explicit ownership transferOwned pointerBig objectsCopy on write

Conclusion

Smart pointers are useful tools for writing safe and efficient code in C . Like any tool, they should be used with appropriate care, thought and knowledge. For a comprehensive and in depth analysis of the issues concerning smart pointers, I recommend reading Andrei Alexandrescu's chapter About Smart Pointers in His Book Modern C Design.

Feel free to use my own smart pointers in your code, and do tell me if you are having any problems with them.The Boost C libraries include some smart pointers, which are more rigorously tested and actively maintained. Do try them first, if they Are Appriate for your Needs.

转载请注明原文地址:https://www.9cbs.com/read-23593.html

New Post(0)