【发布时间】:2014-03-31 15:09:21
【问题描述】:
我有一个类的稍微复杂的数据成员,如下所述:
class BranchOutputRow
{
...
}
class Foo
{
public:
// Slightly complex data member here
std::map<boost::multiprecision::cpp_int, std::set<BranchOutputRow>> hits;
void DoLoop1()
{
// This loop calls the std::pair<> constructor
std::for_each(hits.cbegin(), hits.cend(),
[&](std::pair<boost::multiprecision::cpp_int,
std::set<BranchOutputRow>> const & hit)
{
...
}
}
void DoLoop2()
{
// This loop does NOT call the std::pair<> constructor
for (std::map<boost::multiprecision::cpp_int,
std::set<BranchOutputRow>>::const_iterator hitsPtr
= hits.cbegin();
hitsPtr != hits.cend();
++hitsPtr)
{
...
}
}
}
int main()
{
Foo foo;
foo.hits[1] = std::set<BranchOutputRow>();
foo.hits[1].insert(BranchOutputRow());
foo.DoLoop1(); // direct access to map object is not available
foo.DoLoop2(); // direct access to map object is available
}
如前所述,我发现 Loop #1 调用了 std::pair 构造函数,尽管 lambda 函数通过引用接受其参数。因此,在循环 1 中,我无法直接访问地图中的对象,而只能访问副本。在我的实际程序中,我需要直接访问;因此,我必须使用 Loop 2 指示的版本。
(事实上,循环 2 不调用std::pair 构造函数 - 这并不奇怪 - 并且确实提供了对地图中对象的直接访问。)
我认为 std::for_each 会经过精心设计,以提供与循环 2 等 for 循环相同的语义,因此不会调用 std::pair 构造函数,而是允许直接访问地图。
为什么循环 1 调用 std::pair 构造函数,尽管 lambda 函数通过引用接受其参数?
【问题讨论】:
-
密钥类型为
const在对中,您的 lambda 参数未反映。我建议使用decltype(hits)::value_type const&。 -
@Xeo - 如果
hits被声明为typedef- 例如typedef std::map<...> MyMap;,hits被定义为MyMap hits;,decltype(hits)::value_type会成功吗?我发现它在没有typedef时有效,但在存在时会出现编译器错误。但也许我做错了什么。