std::for_each是通过值传递还是通过引用传递
Does std::for_each pass by value or by reference?
我有一个测试映射,其中包含一对std::string和Person指针
class MyMap {
public:
void clear() {
std::for_each(people.begin(), people.end(),std::bind1st(std::mem_fun(&MyMap::remove), this));
}
void remove(std::pair<std::string, Person*> p) { delete p.second; }
private:
std::map<name, Person*> people;
};
我的问题是for_each是否通过ref或value传递每个Person对?值得用我自己的吗,这个有点干净。
除此之外,如果我想使用boost::bind或std::bind(c++11)而不是bind1st,我该怎么做?这个函数应该像具有继承std::unary_function的operator()的结构一样吗?
映射的类型为std::map<name, Person*>
,但remove
函数的参数为std::pair<std::string, Person*>
。除非name
是std::string
的typedef,否则这将不起作用。
按照当前定义remove
函数的方式,您将复制map
的value_type
。将函数签名更改为:
void remove(std::pair<const std::string, Person *>& p)
// ^^^^^ ^
// key must be const take a reference
使用std::bind
而不是std::bind1st
std::for_each( people.begin(),
people.end(),
std::bind( &MyMap::remove, this, std::placeholders::_1 ) );
但是,如果您可以使用C++11功能,就不需要std::bind
,lambda会更好。
std::for_each( people.begin(),
people.end(),
[]( decltype(*people.begin())& p ) { delete p.second; } );
或者使用基于范围的环路
for( auto&& p : people ) {
delete p.second;
}
for_each
将根据您定义函子的方式,通过值或引用调用函子。
例如:
struct Gizmo
{
bool operator() (const Zippy& rhs) const
{
// ...
}
};
这个函数由ref调用。但是:
struct Gizmo
{
bool operator() (Zippy rhs) const
{
// ...
}
};
这个是按值调用的。
相关文章:
- 为什么可以将左值传递给"std::async",即使它引用了右值
- 无法取消引用值初始化迭代器
- 当值传递给C++中的运算符重载函数时会发生什么
- 访问对象的取消引用值的语法
- 如何访问对象的成员变量的取消引用值
- 为什么双精度引用值在分配给C++中的浮点变量时不会更改
- 为什么我们不允许将纯引用参数传递给 std::thread,但允许传递原始指针?
- C++复制按引用返回和按常量引用值返回
- 在智能指针的反引用值上调用 std::move()
- 如何将非可变参数值传递给 fmt::format?
- 将 qml 项目值传递给 cpp 后如何与它们进行交互?
- NDK:将文本字段值传递给 c++ 字符串
- 错误:无法取消引用值初始化的矢量迭代器
- 从函数返回shared_ptr的取消引用值
- 如何将值传递给 lambda 函数
- 如何在C++中将std::string值传递给RegSetValueEx()
- 模板编译错误:"X"不引用值
- 从共享指针的取消引用值中获取共享指针
- 如何将 c ++ 变量的值传递给 hadoop HDFS 的 bash 系统命令?
- 重写指向抽象类的指针的引用值无效