Auto ptr

Last updated

In the C++ programming language, auto_ptr is an obsolete smart pointer class template that was available in previous versions of the C++ standard library (declared in the <memory> header file), which provides some basic RAII features for C++ raw pointers. It has been replaced by the unique_ptr class.

Contents

The auto_ptr template class describes an object that stores a pointer to a single allocated object that ensures that the object to which it points gets destroyed automatically when control leaves a scope. [1]

The characteristics of auto_ptr are now considered unsatisfactory: it was introduced before C++11's move semantics, so it uses copying for what should be done with moves (and confusingly sets the copied-from auto_ptr to a NULL pointer). These copy semantics mean that it cannot be used in STL containers. [2]

The C++11 standard made auto_ptr deprecated, replacing it with the unique_ptr class template. [3] [4] auto_ptr was fully removed in C++17. [5] For shared ownership, the shared_ptr template class can be used. shared_ptr was defined in C++11 and is also available in the Boost library for use with previous C++ versions. [6]

Declaration

The auto_ptr class is declared in ISO/IEC 14882, section 20.4.5 as:

namespacestd{template<classY>structauto_ptr_ref{};template<classX>classauto_ptr{public:typedefXelement_type;// 20.4.5.1 construct/copy/destroy:explicitauto_ptr(X*p=0)throw();auto_ptr(auto_ptr&)throw();template<classY>auto_ptr(auto_ptr<Y>&)throw();auto_ptr&operator=(auto_ptr&)throw();template<classY>auto_ptr&operator=(auto_ptr<Y>&)throw();auto_ptr&operator=(auto_ptr_ref<X>)throw();~auto_ptr()throw();// 20.4.5.2 members:X&operator*()constthrow();X*operator->()constthrow();X*get()constthrow();X*release()throw();voidreset(X*p=0)throw();// 20.4.5.3 conversions:auto_ptr(auto_ptr_ref<X>)throw();template<classY>operatorauto_ptr_ref<Y>()throw();template<classY>operatorauto_ptr<Y>()throw();};}

Semantics

The auto_ptr has semantics of strict ownership, meaning that the auto_ptr instance is the sole entity responsible for the object's lifetime. If an auto_ptr is copied, the source loses the reference. For example:

#include<iostream>#include<memory>usingnamespacestd;intmain(intargc,char**argv){int*i=newint;auto_ptr<int>x(i);auto_ptr<int>y;y=x;cout<<x.get()<<endl;// Print NULLcout<<y.get()<<endl;// Print non-NULL address ireturn0;}

This code will print a NULL address for the first auto_ptr object and some non-NULL address for the second, showing that the source object lost the reference during the assignment (=). The raw pointer i in the example should not be deleted, as it will be deleted by the auto_ptr that owns the reference. In fact, new int could be passed directly into x, eliminating the need for i.

Notice that the object pointed by an auto_ptr is destroyed using operator delete; this means that you should only use auto_ptr for pointers obtained with operator new. This excludes pointers returned by malloc/calloc/realloc , and pointers to arrays (because arrays are allocated by operator new[] and must be deallocated by operator delete[]).

Because of its copy semantics, auto_ptr may not be used in STL containers that may perform element copies in their operations.

See also

Related Research Articles

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class declaration to reference via a generic variable another different class without creating full declaration for each of these different classes.

In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.

In computer science, a smart pointer is an abstract data type that simulates a pointer while providing added features, such as automatic memory management or bounds checking. Such features are intended to reduce bugs caused by the misuse of pointers, while retaining efficiency. Smart pointers typically keep track of the memory they point to, and may also be used to manage other resources, such as network connections and file handles. Smart pointers were first popularized in the programming language C++ during the first half of the 1990s as rebuttal to criticisms of C++'s lack of automatic garbage collection.

<span class="mw-page-title-main">Pointer (computer programming)</span> Object which stores memory addresses in a computer program

In computer science, a pointer is an object in many programming languages that stores a memory address. This can be that of another value located in computer memory, or in some cases, that of memory-mapped computer hardware. A pointer references a location in memory, and obtaining the value stored at that location is known as dereferencing the pointer. As an analogy, a page number in a book's index could be considered a pointer to the corresponding page; dereferencing such a pointer would be done by flipping to the page with the given page number and reading the text found on that page. The actual format and content of a pointer variable is dependent on the underlying computer architecture.

A function pointer, also called a subroutine pointer or procedure pointer, is a pointer referencing executable code, rather than data. Dereferencing the function pointer yields the referenced function, which can be invoked and passed arguments just as in a normal function call. Such an invocation is also known as an "indirect" call, because the function is being invoked indirectly through a variable instead of directly through a fixed identifier or address.

In the C++ programming language, a copy constructor is a special constructor for creating a new object as a copy of an existing object. Copy constructors are the standard way of copying objects in C++, as opposed to cloning, and have C++-specific nuances.

In computer programming, run-time type information or run-time type identification (RTTI) is a feature of some programming languages that exposes information about an object's data type at runtime. Run-time type information may be available for all types or only to types that explicitly have it. Run-time type information is a specialization of a more general concept called type introspection.

In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C. The name C++ reference may cause confusion, as in computer science a reference is a general concept datatype, with pointers and C++ references being specific reference datatype implementations. The definition of a reference in C++ is such that it does not need to exist. It can be implemented as a new name for an existing object.

In some programming languages, const is a type qualifier that indicates that the data is read-only. While this can be used to declare constants, const in the C family of languages differs from similar constructs in other languages in being part of the type, and thus has complicated behavior when combined with pointers, references, composite data types, and type-checking. In other languages, the data is not in a single memory location, but copied at compile time on each use. Languages which use it include C, C++, D, JavaScript, Julia, and Rust.

C++/CLI is a variant of the C++ programming language, modified for Common Language Infrastructure. It has been part of Visual Studio 2005 and later, and provides interoperability with other .NET languages such as C#. Microsoft created C++/CLI to supersede Managed Extensions for C++. In December 2005, Ecma International published C++/CLI specifications as the ECMA-372 standard.

In object-oriented programming, a destructor is a method which is invoked mechanically just before the memory of the object is released. It can happen when its lifetime is bound to scope and the execution leaves the scope, when it is embedded in another object whose lifetime ends, or when it was allocated dynamically and is released explicitly. Its main purpose is to free the resources which were acquired by the object during its life and/or deregister from other entities which may keep references to it. Use of destructors is needed for the process of Resource Acquisition Is Initialization (RAII).

A class in C++ is a user-defined type or data structure declared with keyword class that has data and functions as its members whose access is governed by the three access specifiers private, protected or public. By default access to members of a C++ class is private. The private members are not accessible outside the class; they can be accessed only through methods of the class. The public members form an interface to the class and are accessible outside the class.

The curiously recurring template pattern (CRTP) is an idiom, originally in C++, in which a class X derives from a class template instantiation using X itself as a template argument. More generally it is known as F-bound polymorphism, and it is a form of F-bounded quantification.

C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by the publication year of the specification, though it was formerly named C++0x because it was expected to be published before 2010.

C++ doesn't have:

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

In the programming language C++, unordered associative containers are a group of class templates in the C++ Standard Library that implement hash table variants. Being templates, they can be used to store arbitrary elements, such as integers or custom classes. The following containers are defined in the current revision of the C++ standard: unordered_set, unordered_map, unordered_multiset, unordered_multimap. Each of these containers differ only on constraints placed on their elements.

In the C++ programming language, placement syntax allows programmers to explicitly specify the memory management of individual objects — i.e. their "placement" in memory. Normally, when an object is created dynamically, an allocation function is invoked in such a way that it will both allocate memory for the object, and initialize the object within the newly allocated memory. The placement syntax allows the programmer to supply additional arguments to the allocation function. A common use is to supply a pointer to a suitable region of storage where the object can be initialized, thus separating memory allocation from object construction.

In C++ computer programming, allocators are a component of the C++ Standard Library. The standard library provides several data structures, such as list and set, commonly referred to as containers. A common trait among these containers is their ability to change size during the execution of the program. To achieve this, some form of dynamic memory allocation is usually required. Allocators handle all the requests for allocation and deallocation of memory for a given container. The C++ Standard Library provides general-purpose allocators that are used by default, however, custom allocators may also be supplied by the programmer.

SymbolicC++ is a general purpose computer algebra system written in the programming language C++. It is free software released under the terms of the GNU General Public License. SymbolicC++ is used by including a C++ header file or by linking against a library.

References

  1. "auto_ptr Class". Microsoft. Retrieved 2006-09-27.
  2. Meyers, Scott (2014). Effective Modern C++: 42 specific ways to improve your use of C++11 and C++14. Sebastopol, CA. p. 118. ISBN   978-1-491-90399-5.{{cite book}}: CS1 maint: location missing publisher (link)
  3. "Working Draft, Standard for Programming Language C++ N3242" (PDF). 28 February 2011. p. 1233. Retrieved 2013-02-17.
  4. Kalev, Danny. "Using unique_ptr, Part I". informIT. Retrieved 30 September 2010.
  5. "Programming Language C++, Library Evolution Working Group JTC1/SC22/WG21 N4190". 2014-10-09. Retrieved 2016-08-29.
  6. "Collecting Shared Objects". Dr. Dobb's. 2004-07-01. Retrieved 2006-09-27.