The STL provides std::copy but it is tricky to use it with output containers with fixed sizes as there is no bounds checking on the output iterator
So I invented my own, something like below
template<class InputIterator , class OutputIterator>
void safecopy( InputIterator srcStart , InputIterator srcEnd ,
OutputIterator destStart , OutputIterator destEnd )
{
while ( srcStart != srcEnd && destStart != destEnd )
{
*destStart = *srcStart;
++srcStart;
++destStart;
}
}
int main()
{
std::istream_iterator<char> begin(std::cin), end;
char buffer[3];
safecopy( begin, end, buffer, buffer + 3 );
return 0;
}
Questions:
- Am I reinventing the wheel here ? Is there an stl algorithm to do what I want.
- Are there any deficiencies in my safecopy , does it work for everything std::copy works for ?
Let me promote my comment to an answer, so I have a bit more space.
First off, your implementation looks good.
Now, why isn’t this in the standard? (The new standard adds
std::copy_n, but that does something different, too.*)Think about it like this:
strncopyisn’t really a “good” idea; it’s just not a terrible idea. Since C doesn’t have any dynamic data structures, a length-checked version is the best you can do.But in C++ this doesn’t fit nicely into the general idea of dynamic containers: You would rarely want to overwrite some elements, but rather create all elements, which you do by
std::copyplusstd::inserter.strncpyis a crutch which requires you to preallocate the destination data structure, but in C++ we can do a lot better than this. With dynamic containers, iterators and inserters, we can copy anything without needing to worry about allocation.In other words, any abstract algorithm that you might conceive should have a better, more specific method of obtaining iterators and iterator ranges (think remove/erase); it is rarely the case that the ultimate goal of an algorithm is to only produce an output range that is constrained by some other destination range.
In summary: Yes, you can do that, but you can probably do better.
*) Though
copy_nplusminof source and destination size could be used to create a bounded copy.