c++中auto_ptr的指针运算

Pointer arithmetic on auto_ptr in C++

本文关键字:指针 运算 ptr auto c++      更新时间:2023-10-16

我正在阅读auto_ptr在c++ STL中的实现。

我看到通常需要的指针操作,如->和*被重载,使它们保持相同的含义。然而,指针算术是否适用于自动指针?

假设我有一个自动指针数组,我希望能够做一些像array + 1这样的事情,并期望获得数组中第二个元素的地址。我怎么得到它?

我对这个要求没有任何实际应用,只是出于好奇问一下。

auto_ptr对象只能指向单个元素,因为它使用delete(而不是delete[])来删除它的指针。

所以这里没有指针运算。

如果你需要一个对象数组,通常的建议是使用std::vector。

您需要在这里查看auto_ptr的文档。

没有为auto_ptr定义指针算术。

auto_ptr<int>  p1(new int(1));  
*p2 = 5;   // Ok
++p2;       // Error, no 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();

在对象数组中向下移动指针仍然是相同的。下面是一个例子:

#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;
}
输出:

1
2