Note that there are some explanatory texts on larger screens.

plurals
  1. POGCC 3.42 and VC2008 treat std::transform differently, take a reference or a copy of the functor?
    primarykey
    data
    text
    <p>I have Googled this functor-related topic, and it seems that people would generally say that the Standard Library will take a functor as a copy by default. Many examples have been found, and this is true for <code>std::for_each</code>. GCC and VC2008 compilers have yielded the same result: both take a copy of the functor.</p> <p>But for <code>std::transform</code> I have found a difference in the testing code below:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; #define MSG(msg) cout &lt;&lt; msg &lt;&lt; endl; struct MyFunctor{ MyFunctor() { MSG("MyFunctor constructor"); } MyFunctor(const MyFunctor&amp; myf) { MSG("MyFunctor copy constructor"); } ~MyFunctor() { MSG("MyFunctor destructor"); } int operator()(int i) { i = -(i+1); return i; } }; int main() { vector&lt;int&gt; myvec; myvec.push_back(1); myvec.push_back(1); myvec.push_back(1); myvec.push_back(1); std::transform(myvec.begin(),myvec.end(),myvec.begin(),MyFunctor()); system("pause"); } /* gcc result: MyFunctor constructor MyFunctor destructor vc2008 result: MyFunctor constructor MyFunctor copy constructor MyFunctor copy constructor MyFunctor destructor MyFunctor destructor MyFunctor destructor */ </code></pre> <p>The result seems to suggest that GCC takes <code>MyFunctor</code> as a reference while vc2008 takes it as a copy (just as both of them treat <code>for_each</code>). </p> <p>Why do GCC and vc2008 behave differently in this matter, and which one should be the right practice?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload