c++中auto_ptr的指针运算
Pointer arithmetic on auto_ptr in C++
我正在阅读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
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 避免指针运算,修复叮当整齐错误
- 如何在 c++ 中使用带有数学运算的引用/指针?
- 在标准布局对象中进行指针运算(例如,使用偏移量)时,我们是否需要使用 std::launder?
- 对已删除的数组进行指针运算仍然合法吗
- LLDB Python脚本中的指针运算
- C++中使用char*的指针运算
- 更正C中的指针运算
- 指针运算正在运行
- C++奇怪的指针运算
- T*与char*指针运算
- 指针运算在数组之外有用途吗?
- 我怎么知道是什么使不完整类型不完整的错误:对指向不完整类型的指针进行算术运算
- c++指针运算的怪异
- c++中auto_ptr的指针运算
- 调试断言失败!使用指针运算的字符串操作
- 限制限定符和指针运算
- std::uintptr_t可以用来避免指针越界运算的未定义行为吗?