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 code will not leak the T no matter whether the function normally or by means of an exception, pt ‘s destructor will be called during stack The cleanup happens automatically.

// use to see the pointer value

assert( pt1 == );

// use release() to take back

Volkswagen Pointer I
Volkswagen Pointer I


Volkswagen Pointer I

Interesting Articles



Смотрите также:

Other articles of the category "Pointer":

Twitter-news
Our partners
Follow us
Contact us
Our contacts

dima911@gmail.com

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.