4

I am C++ noob studying functors. I have this code as below(NB - This is not my homework, i am past that!).

It does print 0 1 2 3 4 5 6 7 8 9 on console
which I dont see how does it maintain the state of this object(value of n) if the functor is called by value and not by reference/pointer

EDIT: I thought here(Example 1) since the functor is called by Value and the constructor initializes n to zero every time. So it should be zero always at beginning, then it should increment to 1 and return 1. How is it printing 0 1 2 3 4 5 6 7 8 9

Example 1]

class g
{
public:
    g():n(0){}
    int operator()() { return n++; }
    int n;
};

;

int main()
{
    int a[10];
    g v1;
    std::generate(a, a+10, g());//This passes a functor to generate 

    //EDIT - this will print 0 1 2 3 4 5 6 7 8 9**
    std::copy(a, a+10, std::ostream_iterator<int>(std::cout, " "));

    getchar();
    return 0;
}

Because I have seen code like below using reference variables inside a functor to retain state, here and developed a simple code using that concept as below:

Example 2]

class CountingFunctor
{
public:
    CountingFunctor() : _counter(0) {}
    int getCounter(void) const {return(_counter);}
    void operator () (Contained item) {if(item.getShouldBeCounted()) _counter++;}
private:
    int _counter;
};
#endif

//this class uses references to maintain state in the functor
class CountingFunctor
{
public:
    CountingFunctor(int &elem) : _counter(elem) {_counter=0;}
    int getCounter(void) const {return(_counter);}
    void operator () (Contained item) {if(item.getShouldBeCounted()) _counter++;}
private:
    int &_counter;
};

int main()
{
    vector<Contained> Container(10);
    Container[3].setShouldBeCounted(false);
    Container[9].setShouldBeCounted(false);
    int elem;
    CountingFunctor CountAllWhoShouldBe(elem);
    std::for_each(Container.begin(), Container.end(), CountAllWhoShouldBe);
    std::cout << CountAllWhoShouldBe.getCounter() << " items should be counted." << std::endl;

    getchar();
}

Question is

So Do functors maintain state of their objects by themselves, i.e. without needing any reference variables as shown in example 2

Or Code in Example 1 is working because std::generate() calls the functor by reference/pointer?

Further reading material appreciated.

6 Answers 6

2

When you call std::generate, it gets its own copy of the functor object. Once inside that function though, it's just calling it's own single instance of the object repeatedly, so state is preserved inside the generate call, but not between generate and the caller.

So, change your code to

g v1;
std::generate(a, a+10, v1);

and afterwards v1.n will still be zero. Inside generate it was operating on its local copy (say v2), which did get incremented, but couldn't tell v1 about it.

Now, if you want to communicate v2's state out to v1, that's when you need to use references inside your functor, so v1 and v2 share whatever state gets mutated inside the call.


We can expand the call to show this more clearly:

g v1;
std::generate(a, a+10, v1);
// -> generate(begin=a, end=a+10, v2=g(v1))
{
    while (begin != end)
        *begin = v2();
}
// v2 just went out of scope, and took the accumulated state with it!
// v1 in the caller's scope remains unchanged

Now it should be obvious that if v1, instead of being a value object which gets deep-copied and keeps its state internally, kept a reference to shared state and was shallow copied, then v2 would share the same state as v1 and that state would be accessible after the call.

In fact, we can write a simple-ish wrapper to automate this, so you don't need to do it by hand for every functor:

template <typename OriginalFunctor, typename RType>
class StatefulFunctor
{
    OriginalFunctor &fun;

public:
    StatefulFunctor() = delete;
    StatefulFunctor(OriginalFunctor &orig) : fun(orig) {}
    StatefulFunctor(StatefulFunctor const &other) : fun(other.fun) {}
    StatefulFunctor(StatefulFunctor &&other) : fun(other.fun) {}

    template <typename... Args>
    RType operator() (Args&&... args)
    {
        return fun(std::forward<Args>(args)...);
    }
};

template <typename RT, typename OF>
StatefulFunctor<OF, RT> stateful(OF &fun)
{
    return StatefulFunctor<OF, RT>(fun);
}

Now changing the original code to:

g v1;
std::generate(a, a+10, stateful<int>(v1));

means v1.i will be updated in place.

As Jerry Coffin points out, preservation of state even inside the call isn't guaranteed, so it's sensible to do something like this with stateful functors even if you don't need the state preserved for the caller.

2
  • Thanks. This is new to me - "generate() gets its own copy of functor object and for repeated calls, for each element in the container it calls that same object..
    – goldenmean
    Feb 21, 2012 at 16:05
  • Yeah - I'm not even certain the standard guarantees it'll use a single copy of the functor inside generate or any other call, but of course regular functions are stateless so it doesn't matter
    – Useless
    Feb 21, 2012 at 16:08
0

Of cause, functor objects do not have any special magic, that differ them from other objects. But I do not see what state functor should save while copting in your example.

Consider first one: Possible generate realization is

template <typename Iterator, typename Functor>
void generate(Iterator begin, Iterator end, Functor f)
{
    for (Iterator it  = begin; it != end; ++it) {
        *it = f();
    }
}

In this example functor copied only once on function entrance, than code deals with local variable f, and it does not perform any copying.

While your functor has memeber n, state is saved in it.

0

Functors are exactly like any other objects - if their member is defined as a reference, they store it by reference, if it's defined as a value, they store a value. Your first example works because std::generate gets its functor parameter by value, not by reference and thus operates on a copy of the temporary you create in the expression with g().

3
  • Exactly if everycall is a local copy of functor, then every time constructor of it initializes it to zero. Am i missing something.
    – goldenmean
    Feb 21, 2012 at 16:02
  • A functor call is effectively a method call - it does not create a copy of the object, on which the method is called (your functor). What creates the copy is passing an object, your functor in this case, to a function as a parameter by value.
    – AndrzejJ
    Feb 21, 2012 at 16:09
  • Think of how a function that takes an int by value works: void foo(int i) { ... - the function creates its own private int, and if it modifies the int (e.g. does ++i), only its private copy is affected. The copy's lifetime is the function call - it does not create a new copy every time you do ++i
    – AndrzejJ
    Feb 21, 2012 at 16:17
0

The generate function takes one instance of the functor and calls it over and over again. So The state preservation is the same as in each normal class. I stripped (and simplified) this out of my compilers (gcc 4.5) headers:

template<typename _ForwardIterator, typename _Generator>
void
generate(_ForwardIterator __first, _ForwardIterator __last,
         _Generator __gen)
{
  // concept requirements -- ommitted for easy reading
  for (; __first != __last; ++__first)
    *__first = __gen();
}

As you can see __gen will be one instance of your functor in your examples.

Note that my compiler optimized your first example so no copy construction was made. When using a named variable instead the copy construction took place.

0

It's depending on behavior that's common, but not guaranteed. Specifically, it's counting on the fact that generate will re-invoke the function object for every value assigned, something like this:

template <class FwdIt, class Generator>
void generate(FwdIt first, FwdIt last, Generator gen) {
    while (first != last) {
        *first = gen();
        ++first;
    }
}

I believe the standard allows that, but I'm quite sure it doesn't guarantee it. At least by my reading of the standard, it would be entirely acceptable for it to do something on this general order instead:

template <class FwdIt, class Generator>
void generate(FwdIt first, FwdIt last, Generator gen) {
    decltype(*first) holder = gen();
    while (first != last) {
        *first = holder;
        ++first;
    }
}

In this case, every item in the range would be assigned the same value. That said, this seems like a rather unusual way to implement generate. I'm pretty sure it's allowed, but don't see much reason to do it.

At the same time, I should point out that there are a couple tiny hints of reasons to do it. The first would be efficiency: it could be cheaper to store the value rather than re-create it N times.

The second would be based on a close (pedantic) reading of the description in the standard (§25.2.6/1):

Effects: Invokes the function object gen and assigns the return value of gen though all the iterators in the range [first, last) or [first, first + n).

Given the way that's worded, you could argue that it's basically saying you only invoke gen once, then assign that one return value to all the iterators in the range, rather than re-invoke it for every iterator in the range. For example, it talks about "the return value", implying that there's only one value, rather than a separate return value for each iterator in the range.

Edit: Re-reading, I think the standard does provide a strong indication that the first is intended though. Reading a bit further down, we get:

Complexity: Exactly last - first (or n) invocations of gen and assignments.

If you were being intentionally perverse, you could still assign all the values from a single invocation, and ignore the returns from the other invocations, but this does make it pretty clear that an implementation like the first one above is what's intended (and the second does not conform as-is).

5
  • You generator would not print 0 1 2 3 4 5 6 7 8 9
    – Lol4t0
    Feb 21, 2012 at 15:46
  • One related question... how the compiler translates the g() in the line "std::generate(a, a+10, g());" to the call the constructor g() and the g() call in the line "decltype(*first) holder = gen();" to the overloaded () operator? Feb 21, 2012 at 15:51
  • @Lol4t0: The first one would (assuming you added code to do the printing, anyway). The second one wouldn't -- and I'm pretty sure both conform with the standard's requirements. Feb 21, 2012 at 15:58
  • @Unni g is a type, so g() creates a temporary and calls its constructor. gen is an instance of type g and thus gen() calls g's function call operator on that instance
    – Fiktik
    Feb 21, 2012 at 16:03
  • Sadly I guess a recursive implementation should also be conforming, and that could use a new instance of the functor for each call to operator()
    – Useless
    Feb 21, 2012 at 20:24
0

Example 1 is working because the functor object (v1) has a member variable (n) which is incremented every time the object is called.

Example 2 is different in that the functor object (v1) only updates a reference to a variable which lives outside the object.

Example 1 is a better object-oriented design because each object of class g that you create will take care of its own counting, while in example 2, it is the caller's responsibility to make sure that the counter is not shared and has at least the same lifespan than the functor object.

2
  • In example 1, the functor is called by Value and the constructor initializes n to zero every time. So it should be zero always at beginning, then it should increment to 1 and return 1. How is it printing 0 1 2 3 4 5 6 7 8 9
    – goldenmean
    Feb 21, 2012 at 15:59
  • The functor is not 'called by value' - there is no such thing. It's passed by value to the std::generate function, but that happens only once - when you call generate. The generate function itself makes multiple calls to operator() of the functor object - but that does not call constructor code, it's just like a normal member function call on an existing object.
    – AndrzejJ
    Feb 21, 2012 at 23:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.