In order to help avoid unnecessary heap allocations of strings inside a class, I have adopted a pattern similar to the following:
#include <algorithm>
using namespace std;
class Person
{
public:
template<typename Iter>
void GetName(Iter iter) const // Allow for caller to provide the buffer
{
const char *name = ...; // Get the name
size_t cchName = ...; // Get the size
copy(&name[0], &name[cchName], iter);
}
string GetName() const // Convenience method
{
string name;
this->GetName(inserter(name, name.end()));
return name;
}
};
However, the code also seems to work perfectly fine when I say
void GetName(const Iter &iter) const // <----- changed to const &
Is there any reason (performance or otherwise) for me to use a const & version of the iterator, or should I just use Iter itself? (I don’t know the convention for iterators, or if there are any implications.) (C++03)
The difference here is same difference as pass by value and pass by reference while calling functions.
When you pass by value an copy of the passed variable gets created and the function uses it.
When you pass by reference, the copy is not made. Also, passing the type as
constguards it against modification to some level(ofcourse hackery can break it).Since In your code example you do not need to iterate using the iterator and just need to pass it to
std::copywhich creates its own copy, So your iterator being aconstdoesn’t matter to it, Hence passing by const reference is better option in your example.