Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer arithmetic on auto_ptr in C++

Tags:

c++

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

I see that commonly needed operations on pointers like -> and * are overloaded so that they retain the same meaning. However, will pointer arithmetic work on auto pointers?

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 2nd element of the array. How do I get it?

I don't have any practical application for this requirement, just asking out of curiosity.

like image 692
xyz Avatar asked Jul 19 '11 15:07

xyz


3 Answers

You need to see the doccumentation of auto_ptr here.

There is no pointer arithmetic defined for auto_ptr.

auto_ptr<int>  p1(new int(1));  
*p2 = 5;   // Ok
++p2;       // Error, no pointer arithmetic
like image 33
Alok Save Avatar answered Nov 19 '22 16:11

Alok Save


An auto_ptr can only point to a single element, because it uses delete (and not delete[]) to delete its pointer.

So there is no use for pointer arithmetic here.

If you need an array of objects, the usual advice is to use a std::vector instead.

like image 144
Bo Persson Avatar answered Nov 19 '22 16:11

Bo Persson


This has actually nothing to do with pointer arithmetics.

// 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();
like image 1
Luc Danton Avatar answered Nov 19 '22 14:11

Luc Danton