Using auto_ptr Effectively — Volkswagen Pointer I

24 Фев 2015 | Author: | Комментарии к записи Using auto_ptr Effectively — Volkswagen Pointer I отключены
Volkswagen Pointer I

Using auto_ptr Effectively

article appeared in C/C++ Journal, 17(10), October .

Most people have of the standard auto_ptr smart facility, but not everyone uses it That’s a shame, because it out that auto_ptr neatly common C++ design and coding and using it well can lead to robust code. This shows how to use auto_ptr correctly to your code safer—and how to the dangerous but common abuses of that create intermittent and bugs.

Why Call It an Auto Pointer?

is just one of a wide array of smart pointers. Many libraries provide more kinds of smart pointers can do wild and wonderful things, managing reference counts to advanced proxy services. of the Standard C++ auto_ptr as the Ford of smart pointers: A simple smart pointer that have all the gizmos and luxuries of or high-performance smart pointers, but does many common well and is perfectly suitable for daily use.

What auto_ptr does is own a allocated object and perform cleanup when the object is no needed. Here’s a simple of code that’s unsafe auto_ptr :

// Example 1(a): code

void f()

T* pt( new T );

/*. more */

delete pt;

Most of us write like this every If f() is a three-line function that do anything exceptional, this may be But if f() never executes the delete either because of an early or because of an exception thrown execution of the function body, the allocated object is not deleted and we a classic memory leak.

A simple way to make Example safe is to wrap the pointer in a pointer-like object that the pointer and that, when deletes the pointed-at object Because this smart is simply used as an automatic (that is, one that’s destroyed when it goes out of scope), reasonably called an auto

// Example 1(b): Safe with auto_ptr

void f()

Volkswagen Pointer I

pt( new T );

/*. more code. */

// cool: destructor is called as it goes out

// of and the object is deleted automatically

Now the will not leak the T object, no whether the function exits or by means of an exception, because pt destructor will always be during stack unwinding. The happens automatically.

// use get() to see the pointer value

pt1 == pt2.get() );

// use release() to take ownership

Volkswagen Pointer I
Volkswagen Pointer I

Volkswagen Pointer I

Interesting Articles

Other articles of the category "Pointer":

Our partners
Follow us
Contact us
Our contacts

Born in the USSR

About this site

For all questions about advertising, please contact listed on the site.

Volkswagen all cars catalog with specifications, pictures, ratings, reviews and discusssions about cars Volkswagen.