为什么序列操作算法谓词由copy传递? [英] Why the sequence-operation algorithms predicates are passed by copy?

查看:155
本文介绍了为什么序列操作算法谓词由copy传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么函数通过复制传递给 算法 函数:

I'm wondering why functors are passed by copy to the algorithm functions:

template <typename T> struct summatory
{
    summatory() : result(T()) {}

    void operator()(const T& value)
    { result += value; std::cout << value << "; ";};

    T result;
};

std::array<int, 10> a {{ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 }};
summatory<int> sum;

std::cout << "\nThe summation of: ";
std::for_each(a.begin(), a.end(), sum);
std::cout << "is: " << sum.result;

我期待以下输出:


总和:1; 1; 2。 3; 5; 8; 13; 21; 34; 55; is:143

The summation of: 1; 1; 2; 3; 5; 8; 13; 21; 34; 55; is: 143

sum.result 包含 0 ,这是在ctor中分配的默认值。实现所需行为的唯一方法是捕获 for_each 的返回值:

But sum.result contains 0, that is the default value assigned in the ctor. The only way to achieve the desired behaviour is capturing the return value of the for_each:

sum = std::for_each(a.begin(), a.end(), sum);
std::cout << "is: " << sum.result;

这是因为函数被复制传递给 for_each (而非引用):

This is happening because the functor is passed by copy to the for_each instead of by reference:

template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );

所以外函子保持不变,而内函数更新并在执行算法(现场演示)后返回,因此会再次复制(或移动)结果

So the outer functor remains untouched, while the inner one (which is a copy of the outer) is updated and is returned after perform the algorithm (live demo), so the result is copied (or moved) again after doing all the operations.

这样做有一个很好的理由,但我不是真正意识到这个设计的理由,所以我的问题是:

There must be a good reason to do the work this way, but I don't really realize the rationale in this design, so my questions are:


  • 为什么序列操作算法的谓词通过copy参考?

  • 在引用传递参考文件前面提供了逐个拷贝的方法有哪些优点?

推荐答案

这主要是因为历史原因。在98年,当整个algo东西使它成为标准的参考有各种各样的问题。这最终通过C ++ 03和更高版本的核心和库DR解决。

It's mostly for historic reasons. At '98 when the whole algo stuff made it into the standard references had all kind of problems. That got eventually resolved through core and library DRs by C++03 and beyond. Also sensible ref-wrappers and actually working bind only arrived only in TR1.

那些尝试使用algos和早期C ++ 98有函数使用ref参数或返回的人可以回忆各种麻烦。自写的algos也很容易受到引用参考的问题的困扰。

Those who tried use algos with early C++98 having functions using ref params or returns can recall all kind of trouble. Self-written algos were also prone to hit the dreaded 'reference to reference' problem.

通过值传递至少工作正常,几乎创造了许多问题 - 并提高了早期的ref和cref帮助你需要调整。

Passing by value at least worked fine, and hardly created many problems -- and boost had ref and cref early on to help out where you needed to tweak.

这篇关于为什么序列操作算法谓词由copy传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆