简体   繁体   English

迭代器是否分配诸如指针之类的内存?

[英]Do the iterators allocate memory such as pointers?

Do the iterators allocate memory such as pointers?迭代器是否分配诸如指针之类的内存?

for example:例如:

vector<int>v(100);
vector<int>::iterator it = v.begin();

Does "it" allocate memory and store the address of the first element of vector 'v' in it? “它”是否分配内存并将向量“v”的第一个元素的地址存储在其中? if so why can't we print the address of 'it' such as pointers?如果是这样,为什么我们不能打印“它”的地址,例如指针?

Iterators are defined by the function they perform.迭代器由它们执行的功能定义。 How they perform that function is a private implementation detail.他们如何执行该功能是一个private实现细节。 If an iterator wants to store an address, it can store an address.如果迭代器想要存储一个地址,它可以存储一个地址。 If it thinks storing the answer to the ultimate question of life, the universe, and everything is useful, it can store 42 somewhere.如果它认为存储生命、宇宙和一切终极问题的答案是有用的,它可以在某处存储 42。 If it wants to allocate 2MB of memory, it can – but end users are likely to notice and complain.如果它想分配 2MB 的内存,它可以——但最终用户可能会注意到并抱怨。 The point is that implementation details are not standardized, and all you can expect from an iterator is a reasonably efficient implementation of its functionality.关键是实现细节没有标准化,您可以从迭代器中期望的是其功能的合理高效实现。

You cannot print an implementation detail because that is not part of the required functionality.您无法打印实现细节,因为它不是所需功能的一部分。 (This is a good thing. The fewer requirements on the iterator, the more freedom an implementation has to make the iterator efficient.) (这是一件好事。对迭代器的要求越少,实现使迭代器高效的自由度就越大。)

If you think the implementation details are critical for your application, you probably want to write your own container and iterator classes so that you are not at the mercy of your library's implementors.如果您认为实现细节对您的应用程序至关重要,您可能希望编写自己的容器和迭代器类,这样您就不会受到库实现者的摆布。

If you are just looking for a debugging aid, you are asking the wrong question.如果您只是在寻找调试帮助,那么您就问错了问题。 It is fairly simple to get the address of the object to which an iterator points, assuming it does actually point to an object.获取迭代器指向的对象的地址相当简单,假设它确实指向一个对象。 Dereference to get the object, then take the address.取消引用以获取对象,然后获取地址。 (The iterator it points to the object whose address is &(*it) .) No need to obsess over implementation details. (迭代器it指向地址为&(*it)的对象。)无需关注实现细节。

There is no dynamic allocation here:这里没有动态分配:

vector<int>::iterator it = v.begin();

You can think of assigning to a pointer.您可以考虑分配给一个指针。 Iterator is not a pointer though to be exact.尽管准确地说,迭代器不是指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM