开发者

Can't pass an iterator to a function which accepts pointer

In "Effective STL" tip 16, it says that we should avoid to pass iterator to a function which accepts a pointer. Could anyone explain the detail for me please?

void doS开发者_运维百科omething(const int* pInts, size_t numInts);
vector<int> v;
...
doSomething(&v[0],v.size()) //correct
doSomething(v.begin(),v.size()) //incorrect


In some early implementations of the standard library iterators were implemented as pointers.

Code that depended on that property stopped working when iterators became non-pointers.

So, you should not pass an iterator where a pointer is expected, because if it compiles then it's just by happen-chance. An iterator is not necessarily a pointer. And if it is a pointer, then it may not necessarily be a pointer in some later version (of the library, compiler, whatever).


It's quite simple.

The function takes a pointer, not an iterator.

If you try to pass an iterator, then the function call should be expected to fail. Square peg, round hole.


Notes:

  • The inverse is not the same, since a pointer can be considered a kind of iterator. Usually, a function taking an iterator can be passed a pointer.

  • Your code may appear to compile in some very specific cases, due to implementation details. Don't let this fool you: it's still the wrong code to write!


Because iterator is simply not a raw pointer(even though some underlying implementation could be pointer). The are many types of iterators: foward, bidirectional, random access. The closest iterator to pointer is a random access iterator like the one vector or deque has.


The entire idea of an iterator is to enable flexible data storage that is not contiguously stored in memory. Incrementing an iterator could, for example, move to another "page" in an array that is stored as separate chunks of elements.

If you call a function that takes a pointer, the called function will simply do pointer arithmetic on the address when you increment it (so it won't follow links in a linked list for example).

Passing an iterator to a function that takes a pointer can't work. Dereferencing the first element then taking its address could work, only if you know for sure that the data in the container is stored contiguously. This would work for a vector, but it can't work if the container is a list.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜