开发者

Pointer arithmetic on auto_ptr in C++

开发者 https://www.devze.com 2023-03-21 04:04 出处:网络
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 arit

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 w开发者_JAVA技巧ork 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.


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.


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


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();


Advancing a pointer down an array of objects still works the same. Here's 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;
}

The output:

1
2
0

精彩评论

暂无评论...
验证码 换一张
取 消