auto - auto_ptr Jonathan Schilling, jls@sco.com This...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
auto_ptr Jonathan Schilling, jls@sco.com This newsletter has not yet mentioned the auto_ptr class found in the new standard library. This template class provides a simple form of local, exception-safe, dynamic memory allocation. Its design has undergone some changes during the standardization process, but is now final. To understand the purpose of auto_ptr, first consider this code: class SomeClass { . .. void foo(); . .. }; void f() { SomeClass* p = new SomeClass(); p->foo(); } Calling function f() causes a memory leak, because the storage acquired by the new operator is never released and the destructor for SomeClass (which may itself release other acquired storage or resources within SomeClass) is never called. Even if the coding of f() is changed to: void f() { SomeClass* p = new SomeClass(); p->foo(); delete p; } the function may still leak, because if an exception is thrown out of the call to foo(), the delete statement will never execute. There are several approaches to getting around this type of problem but the one that best preserves the structure of the code is to use the standard library's auto_ptr class, like this: #include <memory> using namespace std;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 3

auto - auto_ptr Jonathan Schilling, jls@sco.com This...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online