Auto_ptr pointer arithmetic in C ++

I am reading an implementation of auto_ptr in C ++ STL.

I see that the usually required operations on pointers like → and * are overloaded, so that they keep the same value. However, will there be an arithmetic pointer on automatic pointers?

Let's say I have an array of auto pointers, and I want to be able to do something like array + 1 and expect to get the address of the second element of the array. How to get it?

I do not have a practical application for this requirement, just asking out of curiosity.

+5
source share
4 answers

Auto_ptr can point to only one element because it uses delete(and not delete[]) to remove its pointer.

.

, std::vector.

+10

auto_ptr .

, auto_ptr.

auto_ptr<int>  p1(new int(1));  
*p2 = 5;   // Ok
++p2;       // Error, no pointer arithmetic
+1

This has nothing to do with pointer arithmetic.

// applies as well with soon-to-be-deprecated std::auto_ptr
typedef std::unique_ptr<T> smart_ptr;

smart_ptr array[42];

// access second element
array[1];
// take address of second pointer
&array[1];
// take address of second pointee
array[1].get();
+1
source

Moving the pointer down the array of objects still works the same way. Here is an example :

#include <memory>
#include <iostream>

int main()
{
  std::auto_ptr<int> foo[3];

  foo[0] = std::auto_ptr<int>( new int(1) );
  foo[1] = std::auto_ptr<int>( new int(2) );
  foo[2] = std::auto_ptr<int>( new int(3) );

  std::auto_ptr<int> *p = &foo[0];

  std::cout << **p << std::endl;
  std::cout << **(p + 1) << std::endl;
}

Output:

1
2
+1
source

All Articles