std::for_each是通过值传递还是通过引用传递

Does std::for_each pass by value or by reference?

本文关键字:引用 值传 std for each      更新时间:2023-10-16

我有一个测试映射,其中包含一对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*>。除非namestd::string的typedef,否则这将不起作用。

按照当前定义remove函数的方式,您将复制mapvalue_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
  {
    // ...
  }
};

这个是按值调用的。