Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7567881
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T14:46:50+00:00 2026-05-30T14:46:50+00:00

I am C++ noob studying functors. I have this code as below(NB – This

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T14:46:52+00:00Added an answer on May 30, 2026 at 2:46 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Noob question here. Please see code below. Where can I read more on this?
noob here i got this jquery code that i found on stackoverflow var maxLines
Noob question. I have this situation where I have these objects: class Address {
PowerShell noob question here. I have groups of servers that are listed in separate
A noob question. I have an alert: alertMessage = This is my message: 1
Python noob; please explain why this loop doesn't exit. for i in range(0,10): print
Noob here. I have a rails app that has users and postings. I need
if (noob.IsChecked) { //blah blah } When I try to use this code to
Complete noob question, so apologies for that. I have two tables, a members table
Noob question, apologies. I'm compiling Java in Windows Vista's command-line and have so many

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.