Discussion Locked

Wrapping an array in a container interface

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

This week's C++ e-newsletter describes how to wrap an array in a container interface. Do you think you'll use the methods illustrated in this tip to disguise a built-in array in a high-level wrapper without changing its low-level nature?

If you aren't subscribed to the free C++ e-newsletter, you can automatically subscribe to it by pasting the following URL into your browser:
http://nl.com.com/MiniFormHandler?brand=builder &subs_channel=bldr_front_door&list_id=e609&tag=fb

* Please delete any extra spaces that appear when you paste this URL into your browser.

3 replies

by leeschoff

My inclination for all single dimension arrays is to simply use an STL vector. That has provided all the functionality I have ever needed.

by dannyk

As explained in the tip, this technique is useful in several cases. First, when you need to interface with C, which of course knows nothing about vectors. Secondly, it's useful in time-critical code, where the overhead of dynamic allocation, reallocation and deallocation are unacceptable or undesirable for some other reasons. Notice that unlike STL vector, this wrapper allocates storage statically and doesn't require explicit deallocation or a destructor.

As always, not every tip is suitable for every program or programmer; if vector serves you well then there's no need to downgrade your code; however, for those who don't consider vector a viable option (and there are many, trust me), this workaround hits the right spot.

by john torjo

std::vector fits the bill.

If you want to use a C-like array, you must know its size. Therefore, you can also use a vector and do a reserve or resize first.

As for the C interface, you can always do:
&*vect.begin(), which will return a pointer to the first element. I have yet to see a vector implementation that does not keep elements contiguously.

And you mentioned exception safe in the title, but not in the description.

Best,
John

This discussion is closed to new replies.