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.
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
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With