我应该使用 const &iterator,还是仅使用迭代器?
为了帮助避免在类中不必要的字符串堆分配,我采用了类似于以下的模式:
#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;
}
};
,代码似乎也工作得很好
void GetName(const Iter &iter) const // <----- changed to const &
但是,当我说是否有任何理由(性能或其他)让我使用时 迭代器的 const & 版本,或者我应该只使用 Iter 本身? (我不知道迭代器的约定,也不知道是否有任何影响。)(C++03)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的区别与调用函数时按值传递和按引用传递的区别相同。
当您按值传递时,将创建所传递变量的副本并由函数使用它。
当您通过引用传递时,不会制作副本。此外,将类型作为 const 传递可以防止其在某种程度上被修改(当然黑客可以破坏它)。
由于在您的代码示例中,您不需要使用迭代器进行迭代,只需将其传递给
std::copy
,它会创建自己的副本,因此您的迭代器是一个const
对此并不重要,因此在您的示例中通过 const 引用传递是更好的选择。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
const
guards 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::copy
which creates its own copy, So your iterator being aconst
doesn't matter to it, Hence passing by const reference is better option in your example.