BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

C++ Tutorial - Class auto_ptr

cplusplus_icon.png




Bookmark and Share





bogotobogo.com site search:




auto_ptr

auto_ptr type is provided by the C++ standard library as a sort of smart pointer that helps to avoid resource leaks when exceptions are thrown.


Here is a typical example which has potential of memory leak.

void memory_leak() 
{
	ClassA * ptr = new ClassA;
	...
	delete ptr;
} 

The reason why this function is source of trouble is that the deletion of the object might be forgotten especially if we have return inside of it. Also an exception would exit the function before the delete statement at the end of the function causing a resource leak.

Usually, we do try to capture all exceptions as in the example below.

void memory_leak() 
{
	ClassA * ptr = new ClassA;
	try {
	...
	}
	catch(...) {
		delete ptr;
		throw;
	}
	delete ptr;
}

As we see in the example, trying to handle the deletion of this object properly in the event of an exception makes the code more complicated and redundant.

So, we need a pointer which can free the data to which it points whenever the pointer itself gets destroyed. Because the pointer is a local variable, it will be destroyed automatically when the function is exited regardless of whether the exit is normal or caused by an exception.

In other words, if an exception occurs after successful memory allocation but before the delete statement executes, a memory leak could occur. The C++ standard provides class template auto_ptr in header file <memory> to deal with this situation.

Our auto_ptr is a pointer that serves as owner of the object to which it refers. So, an object gets destroyed automatically when its auto_ptr gets destroyed.

The function in the 1st example can be rewritten using auto_ptr

#include <memory>
void memory_leak() 
{
	std::auto_ptr<ClassA> ptr(new ClassA);
	...
} 

The delete statement and catch clause are no longer needed.

An auto_ptr has the same interface as an ordinary pointer. Operator * dereferences the object and operator -> provides access to a member if the object is a class or a structure.

But the pointer arithmetic such as ++ is not defined.

One more thing we should be careful about the usage of the pointer is that auto_ptr does not allow us to initialize an object with an ordinary pointer by using the assignment syntax. So, we must initialize the auto_ptr directly by using its value.

	std::auto_ptr<ClassA> ptr1(new ClassA);	        // RIGHT
	std::auto_ptr<ClassA> ptr1 = new ClassA;	// WRONG

Here is the example of auto_ptr in action:

#include <iostream>
#include <memory>

using namespace std;

class Double
{
public:
	Double(double d = 0) : dValue(d) { cout << "constructor: " << dValue << endl; } 
	~Double() { cout << "destructor: " << dValue << endl; }
	void setDouble(double d) { dValue = d; }
private:
	double dValue;
}; 

int main()
{
	auto_ptr<Double> ptr(new Double(3.14));
	(*ptr).setDouble(6.28); 
	return 0;
}

The example creates auto_ptr object ptr and initializes it with a pointer to a dynamically allocated Double object.

Because ptr is a local automatic variable in main(), ptr is destroyed when main terminates. The auto_ptr destructor forces a delete of the Double object pointed to by ptr, which in turn calls the Double class destructor. The memory that Double occupies is released. The Double object will be deleted automatically when the auto_ptr object's destructor gets called.

Only one auto_ptr at a time can own a dynamically allocated object. Thus, the object cannot be an array. By using its overloaded assignment operator or copy constructor, an auto_ptr can transfer ownership of the dynamic memory it manages. The last auto_ptr object that maintains the pointer to the dynamic memory will delete the memory. This makes auto_ptr an ideal mechanism for returning dynamically allocated memory to client code. When the auto_ptr goes out of scope in the client code, the auto_ptr's destructor deletes the dynamic memory.

Though std::auto_ptr is responsible for managing dynamically allocated memory and automatically calls delete to free the dynamic memory when the auto_ptr is destroyed or goes out of scope, auto_ptr have some limitations.

  1. An auto_ptr can't point to an array. When deleting a pointer to an array we must use delete[] to ensure that destructors are called for all objects in the array, but auto_ptr uses delete.
  2. It can't be used with the STL containers-elements in an STL container. When an auto_ptr is copied, ownership of the memory is transferred to the new auto_ptr and the original is set to NULL. In other words, auto_ptrs don't work in STL containers because the containers, or algorithms manipulating them, might copy the stored elements. Copies of auto_ptrs aren't equal because the original is set to NULL after being copied. An STL container may make copies of its elements, so you can't guarantee that a valid copy of the auto_ptr will remain after the algorithm processing the container's elements finishes.

An auto_ptr is simply an object that holds a pointer for us within a function. Holding a pointer to guarantee deletion at the end of a scope is what auto_ptr is for, and for other uses requires very specialized skills from a programmer.

The Boost.Smart_ptr library provides additional smart pointers to fill in the gaps where auto_ptrs don't work. TR1 includes two of the six types of smart pointers in the Boost.Smart_ptr library, namely shared_ptr and weak_ptr. These smart pointers are not meant to replace auto_ptr. Instead, they provide additional options with different functionality.


For more on auto_ptr, see smart pointers












Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






C++ Tutorials

C++ Home

Algorithms & Data Structures in C++ ...

Application (UI) - using Windows Forms (Visual Studio 2013/2012)

auto_ptr

Binary Tree Example Code

Blackjack with Qt

Boost - shared_ptr, weak_ptr, mpl, lambda, etc.

Boost.Asio (Socket Programming - Asynchronous TCP/IP)...

Classes and Structs

Constructor

C++11(C++0x): rvalue references, move constructor, and lambda, etc.

C++ API Testing

C++ Keywords - const, volatile, etc.

Debugging Crash & Memory Leak

Design Patterns in C++ ...

Dynamic Cast Operator

Eclipse CDT / JNI (Java Native Interface) / MinGW

Embedded Systems Programming I - Introduction

Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora

Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain

Exceptions

Friend Functions and Friend Classes

fstream: input & output

Function Overloading

Functors (Function Objects) I - Introduction

Functors (Function Objects) II - Converting function to functor

Functors (Function Objects) - General



Git and GitHub Express...

GTest (Google Unit Test) with Visual Studio 2012

Inheritance & Virtual Inheritance (multiple inheritance)

Libraries - Static, Shared (Dynamic)

Linked List Basics

Linked List Examples

make & CMake

make (gnu)

Memory Allocation

Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.

Multi-Threaded Programming II - Native Thread for Win32 (A)

Multi-Threaded Programming II - Native Thread for Win32 (B)

Multi-Threaded Programming II - Native Thread for Win32 (C)

Multi-Threaded Programming II - C++ Thread for Win32

Multi-Threaded Programming III - C/C++ Class Thread for Pthreads

MultiThreading/Parallel Programming - IPC

Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)

Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)

Multithread Debugging

Object Returning

Object Slicing and Virtual Table

OpenCV with C++

Operator Overloading I

Operator Overloading II - self assignment

Pass by Value vs. Pass by Reference

Pointers

Pointers II - void pointers & arrays

Pointers III - pointer to function & multi-dimensional arrays

Preprocessor - Macro

Private Inheritance

Python & C++ with SIP

(Pseudo)-random numbers in C++

References for Built-in Types

Socket - Server & Client

Socket - Server & Client 2

Socket - Server & Client 3

Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)

Stack Unwinding

Standard Template Library (STL) I - Vector & List

Standard Template Library (STL) II - Maps

Standard Template Library (STL) II - unordered_map

Standard Template Library (STL) II - Sets

Standard Template Library (STL) III - Iterators

Standard Template Library (STL) IV - Algorithms

Standard Template Library (STL) V - Function Objects

Static Variables and Static Class Members

String

String II - sstream etc.

Taste of Assembly

Templates

Template Specialization

Template Specialization - Traits

Template Implementation & Compiler (.h or .cpp?)

The this Pointer

Type Cast Operators

Upcasting and Downcasting

Virtual Destructor & boost::shared_ptr

Virtual Functions



Programming Questions and Solutions ↓

Strings and Arrays

Linked List

Recursion

Bit Manipulation

Small Programs (string, memory functions etc.)

Math & Probability

Multithreading

140 Questions by Google



Qt 5 EXPRESS...

Win32 DLL ...

Articles On C++

What's new in C++11...

C++11 Threads EXPRESS...

Go Tutorial

OpenCV...








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master