auto_ptr::operator=


public member function
auto_ptr& operator= (auto_ptr& a) throw();
template <class Y>
  auto_ptr& operator= (auto_ptr<Y>& a) throw();
auto_ptr& operator= (auto_ptr_ref<X> r) throw();

Release and copy auto_ptr

Copies the value of the pointer held by a (or r).

The object on the left-hand side takes ownership of the pointer (i.e., it is now in charge of freeing the memory block when destroyed). The auto_ptr object on the right-hand side is automatically released (i.e., it is set to point to the null pointer) after the copy.

Notice however that the left-hand side object is not automatically deallocated when it already points to some object. You can explicitly do this by calling member function reset before assigning it a new value.

Parameters

a
An auto_ptr object.
When the types held by the origin and destination auto_ptrs are different (second constructor version), an implicit conversion must exist between their pointer types.
r
An auto_ptr_ref object (a reference to auto_ptr).
X is auto_ptr's template parameter (i.e., the type pointed).


Return value

A pointer to the element pointed (same as member auto_ptr::get).

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// auto_ptr::operator= example
#include <iostream>
#include <memory>
using namespace std;

int main () {
  auto_ptr<int> p;
  auto_ptr<int> p2;

  p = auto_ptr<int> (new int);

  *p = 11;

  p2 = p;

  cout << "p2 points to " << *p2 << "\n";
  // (p is now null-pointer auto_ptr)

  return 0;
}


Output:

p2 points to 11


See also