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 7218003
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T21:25:32+00:00 2026-05-28T21:25:32+00:00

This is the javascript closure code I saw at Javascript Definitive Guide. I’d like

  • 0

This is the javascript closure code I saw at Javascript Definitive Guide. I’d like to write it as C++11

var uniqueID1 = (function()
{
    var id = 0;
    return function() { return id++; };
})();    

This is the cpp code I wrote. But it isn’t be compiled. Can C++11 represent the same expression?

auto c = []() -> int (*)() { int x = 0; return [&x]() -> int { return x++; }};

I’m using VS2010

Edit:
This is the full javascript sample code I made. You can test easily how the code works at your web browser.

<head>
<script language="javascript">
var uniqueID1 = (function()
{
    var id = 0;
    return function() { return id++; };
})();

var uniqueID2 = (function()
{
      var id = 0;
      return function() { return id++; };
})();
</script>
</head>

<body>
        <input value = "uniqueid1" type="button" OnClick="alert(uniqueID1());"></input>
        <input value = "uniqueid2" type="button" OnClick="alert(uniqueID2());"></input>
</body>
</html>
  • 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-28T21:25:33+00:00Added an answer on May 28, 2026 at 9:25 pm

    OK, first let’s break down what your JavaScript does.

    function()
    {
        var id = 0;
        return function() { return id++; };
    }
    

    This creates a function. A function with no name, which takes no parameters. This function, when called, will return a new function. The inner function will have access to a locally scoped variable, and this variable will be part of the state of that inner function.

    Each time this function is called, it will return a new function. That new function will have its own state (var id = 0; has to do something, after all). Each call of the outer function will return a new function with new state.

    This:

    (function()
    {
        var id = 0;
        return function() { return id++; };
    })
    

    Wraps the function in a pair of parenthesis. This is needed for operator precedence rules, to allow this to work:

    (function()
    {
        var id = 0;
        return function() { return id++; };
    })()
    

    This creates a function, and then calls the function. That’s what the last () do at the end. It calls the outer function, which creates an inner function with its own scope and returns it.

    In this expression, the outer function is lost. It’s gone; you can’t access it anymore. You created it for just long enough to call it, then let it drop into the trashcan of garbage collection.

    Given all of this, we can see that this statement:

    var uniqueID1 = (function()
    {
        var id = 0;
        return function() { return id++; };
    })();
    

    Creates the outer function, calls the function which returns a new function, and then stores the inner function in a variable called uniqueID1.

    If you need proof that this is true, try this in your HTML:

    var uniqueMaker = function()
    {
        var id = 0;
        return function() { return id++; };
    };
    
    var uniqueID1 = uniqueMaker();
    var uniqueID2 = uniqueMaker();
    

    You’ll get the same answer as your copy-and-paste version.

    If we want C++ code to mimic this, we need to perform each step with proper C++ code.

    First, the inner function. In C++, lexical scoping does not exist. So you cannot return functions that reference variables in other scopes. You can only return a lambda that has a copy of variables from another scope. Also, lambdas cannot modify scope unless you explicitly allow it. Thus, the inner code must look like this:

    int id = 0;
    return [=]() mutable { return ++id; };
    

    That’s all well and good, but now we need to create a lambda that will return this stateful lambda function. In C++, functions that have state are not the same as function pointers. And since the type of a lambda is compiler-defined, there’s no way to type its name. Therefore, we must employ std::function as the return type of the outer function.

    []() -> std::function<int()>
    {
      int x = 0;
      return [=]() mutable { return x++; };
    }
    

    This creates a lambda function that, when called, will return an inner function with its own state. State that is independent from any subsequent calls to this function. Just like the JavaScript example.

    Now, that’s not enough. Remember, your JavaScript creates the outer function, calls it, and stores only its return value. The outer function itself is discarded. So we need to mimic this. Fortunately, this is easy enough in C++; it looks just like JavaScript:

    ([]() -> std::function<int()>
    {
      int x = 0;
      return [=]() mutable { return x++; };
    })()
    

    Lastly, we stick it in a variable:

    auto uniqueID1 = ([]() -> std::function<int()>
    {
      int x = 0;
      return [=]() mutable { return x++; };
    })();
    

    The type of uniqueID1 will be std::function<int()>. It won’t be the type of the outer function. The outer function is just a temporary that was used to create the inner scope.

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

Sidebar

Related Questions

Why does this code: function answer(x) { function closure() { var x = x
Possible Duplicate: JavaScript scope and closure What is this for? (function(){ //The code to
I have this JavaScript code: for (var idx in data) { var row =
I took this from Google Code Playground http://code.google.com/apis/ajax/playground/ /*CLOSURE * When a function is
Passing this code through jsHint: var A = function (spec) { use strict; var
This javascript code does not work in IE8, but works in Firefox and Google
Why does this javascript return 108 instead of 2008? it gets the day and
I came across this JavaScript function and I don't understand quite what it's doing,
I got this javascript code from off the internet. It's a script that changes
i have this javascript code to which i want to add the jquery fade-in

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.