Lambda in C++ 11

Share the Article

Lambda in C++ consist of expressions and statements (popularly called Lambda expressions). These expressions cause compilers to generate internal classes. Such internal classes are called Closure Class. Finally, from the closure class, C++ compiler instantiate objects during runtime. These runtime-objects are similar to ordinary objects but they encapsulate the lambda functionality. The lambda expressions, become part of source code of the closure classes.

The terms, lambda, closure, closure-classes generally are used interchangeably.

Example of simplest lambda is:

auto lambda = [](){};

Other example:

int x, y; auto c1 = [x](int y) { return x * y > 55; };

In the above statement, the statement on the right-hand side is Lambda expression. Finally, c1 is the runtime object. The program will use this c1 to get the functionality defined by lambda.

The lambda in C++ contains 2 capture modes, by-reference and by-value capture mode.

By-Reference Capture Mode

By-reference capture mode will cause a closure class to create the member variables of reference type. These references point to local variables which are present in the same scope as lambda. To enable creation of by-reference, the square brackets use ampersand [&].

The following example forms a basic lambda with by-reference mode. The variable “tmp” inside lambda becomes reference to local variable “tmp” in initialize function.

#include <iostream> //main header #include <functional> //for function ptr using namespace std; //namespace std::function<void()> fp; void initfunda() { std::string tmp = "temporary string"; cout << "Address in function = " << &tmp << endl; fp = [&](){ cout<<"Address in lambda = " <<&tmp<<endl; }; fp(); //call lambda } int main() { initfunda(); return 0; }

The output from compiler shows variable “tmp” has same address both outside and inside the class.

Lambda functions with reference capture

There is another way to enable by-reference, i.e. by explicit reference of “tmp”. The following code snippet uses explicit reference.

fp = [&tmp](){ cout<< "Address in lambda = "<<&tmp<<endl; };

By-value capture mode

By-value capture mode will cause a closure class to create copies of local variables. Therefore, the local variables which are in the same scope just copies. To enable by-value, the square brackets use equal-to sign [=].

The following example forms a basic lambda with by-value mode. The variable “tmp” inside lambda becomes copy of local variable “tmp” in initialize function.

#include <iostream> //main header #include <functional>//for function ptr using namespace std; //namespace std::function<void()> fp; void initfunda() { std::string tmp = "temporary string"; cout << "Address in function = " << &tmp << endl; fp = [=](){ cout <<"Address in lambda = "<<&tmp<<endl; }; fp(); //call lambda } int main() { initfunda(); return 0; }

The output of program shows that both the “tmp” variables have different addresses.

Lambda function with by value capture mode

Just like explicit by-reference, there is similar format for explicit by value.

fp = [tmp](){ cout << "Address in lambda = "<<&tmp<< endl;};

Capture by-value with class objects

In case, the local variables are objects, then for doing by-value capture, compiler shall call copy-constructor to create copy of objects. The following example illustrates this.

#include <iostream> //main header #include <functional>//for function ptr using namespace std; //namespace class MainFunda { public: MainFunda() { cout << "MainFunda()\n"; } MainFunda(const MainFunda&) { cout << "MainFunda(const MainFunda&)\n"; } ~MainFunda() { cout << "~MainFunda()\n"; } }; int main() { MainFunda a1; auto fp = [a1](){ }; //Invoke copy constructor return 0; }

The output shows copy constructor called for copying object a1 in lambda closure.

Lambda function capture class object by value

Capture do not happen for static variables in local scope

The following examples shows that “tmp” is now static variable. Therefore, no copy of “tmp” happens inside closure class. The lambda expression shall be calling the actual static variable even with by-value capture mode.

#include <iostream> //main header #include <functional> //for function ptr using namespace std; //namespace std::function<void()> fp; void initfunda() { static std::string tmp = "temporary string"; cout << "Address in function = " << &tmp << endl; fp = [=](){ cout <<"Address in lambda = "<<&tmp<<endl; }; fp(); //call lambda } int main() { initfunda(); return 0; }

The output shows that address of “tmp” inside lambda is same as address of static variable “tmp”.

lambda function trying to capture static variable

When capture by-reference and reference variable goes out of scope

The capture by-reference mode should be used very carefully. This is because, there is a possibility that lifetime of lambda shall out-live the scope of local variables. In following example, “fp” is global variable so the lambda will live till the program is running. However, local variable “tmp” will be destroyed the moment initialize function returns. Hence, reference to “tmp” will become dead inside lambda. Thereafter, any use of “tmp” will have undefined behavior.

#include <iostream> //main header #include <functional>//for function ptr using namespace std; //namespace std::function<void()> fp; void initfunda() { std::string tmp = "temporary string"; fp = [&](){ cout << "Executing Lambda : " << tmp << endl; }; fp(); //Valid Call } int main() { initfunda(); fp(); //Invalid Call return 0; }

The output shows that when main function calls lambda, then it prints garbage value for “tmp”.

by reference capture variable goes out of scope

Use static variable or capture by-copy to solve the problem

The following problem solves the problem of by-reference by making the tmp variable as static. Therefore, “tmp” will live till this program is running.

#include <iostream> //main header #include <functional>//for function ptr using namespace std; //namespace std::function<void()> fp; void initfunda() { static std::string tmp = "temporary string"; fp = [&](){ cout <<"Executing Lambda : "<<tmp<< endl; }; fp(); //Valid Call } int main() { initfunda(); fp(); //Valid Call return 0; }


Lambda function with static in c++

Capture by-reference of non-automatic variables

Capture should happen only for local variables. When the program forcefully passes a global variable for capture, then compiler shall give error.

#include <iostream> //main header #include <functional>//for function ptr using namespace std; //namespace std::function<void()> fp; std::string tmp = "temporary string"; //global void initfunda() { fp = [&tmp](){ cout<<"Executing Lambda : "<<tmp<<endl; }; fp(); //call lambda } int main() { initfunda(); fp(); //call lambda return 0; }

However, Some newer compiler may generate warning instead of error.

compiler error for lambda capturing global variable in c++

Same rule applies on by-value capture.

The following code snippet uses tmp to enable capture by-value.

fp = [tmp](){ cout << "Executing Lambda : "<< tmp << endl; };


compiler error for lambda value capture with global variable

Move object inside Lambda

In C++14, there is better capture mode which has more flexibility. This is generalized or init capture mode. The following program uses generalized capture mode to move an object to lambda. This mode can achieve what by-reference and by-value mode cannot.


[<Name of Data member in closure class> = <Expression>]

#include <iostream> //main header #include <functional>//for function ptr using namespace std; //namespace std::function<void()> fp; std::string tmp = "temporary string"; //works for non-local too void initfunda() { fp = [tmp=std::move(tmp)]() { cout << "Executing Lambda : " << tmp << endl; }; fp(); //call lambda } int main() { cout << "tmp = " << tmp << endl; initfunda(); cout << "tmp = " << tmp << endl; fp(); return 0; }

The output shows that when program moves “tmp” inside lambda, then it becomes available only on invocation of lambda and not outside it.

move object inside lambda function in c++

Main Funda: Lambda in C++ is another way to create function objects

Related Topics:

Lambda in C++14
Lambda in C++17
What are the drawbacks of using enum ?
Which member functions are generated by compiler in class?
How to stop compiler from generating special member functions?
Compiler Generated Destructor is always non-virtual
How to make a class object un-copyable?
Why virtual functions should not be called in constructor & destructor ?
Explaining C++ casts
How pointer to class members are different ?
How std::forward( ) works?
Rule of Three
How std::move() function works?
What is reference collapsing?
How delete keyword can be used to filter polymorphism
emplace_back vs push_back

Share the Article

5,580 thoughts on “Lambda in C++ 11

  1. 苹果的德州扑克又回来了!为了庆祝App Store成立10周年,我们带回了其首批游戏之一,一款颇受欢迎的经典游戏。最初是为iPod制作,然后带到iPhone,粉丝们会喜欢抛光的重新设计,包括新角色,更具挑战性的游戏玩法,以及支持最新iPhone和iPod touch的精美图像。玩家第一次免费玩的话也会喜欢它。 欢乐德州扑克app让你能够获得众多的游戏功能,玩家可以和你的好朋友一起约会,在这里建造私人房间,调整游戏中的游戏规则,让你们玩到最经典的棋牌游戏。 喜欢这种风格游戏的玩家们,不妨下载欢乐德州扑克app畅玩一下吧! 「鲍老儿」,淳正之态。果然道:百宝装腰带,珍珠络 换换现金的棋牌游戏 元神天仙境 他们开始追求更高的社交体验,对于生活品质的追求不舍。服务于男士的品牌店从barbershop,到男士香氛店、买手店等都在暴涨。 百乐德州扑克还不错啊,支持手机还可以兑换现, 德州牌扑克游戏APP拥有全网最全的德州棋牌玩法,更有热门的德州扑扑克游戏,非常精彩好玩,是2022年度被授予最佳棋牌平台之一的APP。德州牌扑克游戏APP拥有超高人气,而且玩的都是真人,随机匹配即可找到牌友对战,展现你的德州牌扑克实力技术。喜欢的朋友可以下载德州牌扑克游戏APP体验。 幽冥境传说是孤魂野鬼的集聚之地,但也是所有人轮回转生的必经之处。《热血江湖手游》跨服PVE神地幽冥境玩法设计理念继承这一传说,场景内遍布魔物、各类BOSS,但高风险同样伴随着高收益。江湖风靡云涌,看各服顶级帮派如何勇克劲敌。神地幽冥境是全新的帮派战玩法,10级以上的帮派方可参与。幽冥境是一个独立的跨服战场,每周二、周四限时开启,战场又划分为两个板块,旨在吸引豪侠们步步深入,抢夺稀世珍宝。第一板块和…

  2. Silnik forum XER-Board Release_1.33 opracowany i stworzony od podstaw przez Reklama: pobierz VulkanBet jest domem dla wielu bonusów, a strona internetowa obiecuje, że będzie ich jeszcze więcej. Obecnie każda dobra strona tego typu gwarantuje swoim nowym graczom hojne gratyfikacji, a VB się na ich tle nie wyróżnia. Poniżej opiszemy, czego możesz się spodziewać po pierwszej promocji i co otrzymasz od razu po utworzeniu swojego konta. Sam możesz ocenić, czy taka propozycja Ci odpowiada. Na naszej stronie znajdziesz nowe Ruletki, Jackpoty jak i pozostałe strony z pozostałymi grami na których możesz grać za swoje skiny CS:GO. Dla każdej strony oferujemy specjalny kod, dzięki któremu otrzymasz darmowe coinsy na start. Choose the game that interests you and play itfor free. Większość stron z ruletkami CS GO, jackpotami CS:GO i otwieraniem darmowych skrzynek oferuję szanse zbierania darmowych coinsów na start. Aby użyć kodu i zebrać darmowe monety na rozpoczęcie swojej przygody z ruletką, wystarczy odnaleźć na stronie zakładkę Affiliate, Free Code, Free Coins. Sposób wpisywania kodu jest nieco inny na każdej stronie, ale wystarczy moment, aby uzyskać darmowe skiny do CS GO. Trafiasz na stronę z codziennymi nagrodami. Pod dużym kołem znajduje się komunikat “Zrealizuj kod polecający (Otrzymaj 500 BUX):”. Krzyśkowi poświęcamy najwięcej miejsca, gdyż to z jego tekstami spotykacie się na co dzień. To on jest również autorem większości z recenzji kasyn prezentowanych na stronie. Krzysiek swoją przygodę z kasynami zaczynał dość wcześnie. Zaraz po studiach wyjechał na Maltę, gdzie pracował jako obsługa klienta w kasynie online. Dzięki temu poznał ten biznes od podszewki i doskonale wie, jak funkcjonują kasyna i czego najbardziej poszukują gracze – bonusy i darmowe spiny. Krzysiek specjalizuje się w pisaniu recenzji i testowaniu gier.

  3. Spin247 casino has some pretty cool jackpot games. In fact, we would go so far as to say the assortment of jackpots surpasses any other category on the site. Choose your favorites from more than 70 jackpot titles, but keep one thing in mind – many of them look like knock-offs of some far more popular slots. For example, Cash Conquest’s imagery strongly resembles the mega-popular Gonzo’s Quest, while Spinburst looks suspiciously similar to Starburst. Unfortunately for Spin247, the originals are far better than these mediocre copies.  Overall a nice, simple casino with games that I haven’t seen in other casinos. Interesting referral bonuses, where the registration of the referral itself gives you cash, plus free spins in the game of the month. Unfortunately I have never withdrawn anything from this casino, I have never managed to win too much, also my opinion is incomplete and the rating will not be the best I could give. Free money no deposit ca casino wintika Casino is bursting at the seams with promotions and bonuses, you need to completely understand the rules of paylines. There are a great many fantastic Canadian online casinos, iTech Labs. Its time to enjoy some of the best NetEnt games again this month at Race Casino, the integration of games will be finished. Yes you can. The idea is that you get to play real money games at the online casino using the No Deposit Bonus funds. You get to try out the games for free without risking your own bankroll, allowing you to test-drive the products ahead of real-money play. Take into account that the online casino won’t give you a huge amount of bonus cash or free spins to play with – it’s usually enough to give you a feel for the site. As such, your winnings will be proportionate to the size of the bonus. 

  4. They are a smart bunch and will help you with your questions regarding medical cannabis. Who needs to report a loss or theft of cannabis, and how to fill out the Loss or theft of cannabis form Account Amendment – Update your personal information. In the most recent report, up to December, 2021, 16.6 million packaged units of cannabis were sold in Canada, including the medical and non-medical sales channels. Inspired Cannabis has retail locations across Canada! Ace Valley is a cannabis brand focused on ready-to-enjoy products. The company offers a wide range of well-designed pre-rolls, vapes and gummies across Canada. Ace Valley gummies are balanced with precise doses of cannabinoids in every bite. Twd. is a Canadian-grown simple brand with one product: cannabis. The brand offers simplified, affordable, high-quality options that make shopping for cannabis easy. It’s easy to see why Twd. are three of the most cost-efficient letters in the industry. Cannabis is illegal in most countries. If you try to travel internationally with any amount of cannabis in your possession, you could face serious criminal penalties both at home and abroad. You could be denied entry at your destination country if you have previously used cannabis or any substance prohibited by local laws. You could also be denied entry to other countries in the future. Under the Cannabis Act, each province and territory is responsible for setting its own rules for how cannabis can be sold, where stores can be located, and how stores must be operated. Provinces and territories may also set additional restrictions they feel are necessary. As a result, the Government of Ontario has worked to implement a safe, legal system for cannabis retail that is intended to protect youth, protect roads and combat the illegal market for cannabis.

  5. Is this really a case of no money down and keep what you win or is there more to these online slots offering real money with no deposit required? Get the most of the real money online casinos with no deposit codes in this list. If you’re looking for the best online casino for Canadian players, look no further. We have gone ahead and combed through hundreds of casinos to find the best and most interesting online casinos. According to our expert ranking criteria, Red Dog is the top online casino right now. It scored high across all the benchmarks – games, bonuses, user experience, and banking methods – and you can play its casino games both for free and real money. There is a major difference between real-money online casino games and social casino gaming options. For one, you can actually win real money in states that offer real online gaming versus on a free social casino platform or app. Poker is an exciting and stimulating hobby, but looking for the best poker sites — not so much. You have so many options on hand, all of them offering too-good-to-be-true bonuses and promising the most exciting tournaments. Poker site accepting bitcoin Hourly Free rolls worth 50$ $10,000 in freerolls 4 times – weekly $2500 guarentee new player freeroll each sunday Usa Players Accepted, big events and over 50,000 player at peak time. online, freeroll tournaments are a gold-mine for poker players. If you’re learning to play poker – freerolls can be a great way to learn hand-rankings, and to get accustomed to playing online without risking any money. Freerolls offer real prizes (cash, satellite seats or other loot – depending on the tournament). Message Index is the world’s leading poker website. Among other things, visitors will find a daily dose of articles with the latest poker news, live reporting from tournaments, exclusive videos, podcasts, reviews and bonuses and so much more.

  6. esomeprazole trental 400 mg tablete cena The Zetas leader and his alleged accomplices were flown to Mexico City, where they are expected to eventually be tried in a closed system that usually takes years to prosecute cases, particularly high profile ones nolvadex The recent approval by the Food and Drug Administration FDA of paroxetine Brisdelle, Noven for the treatment of moderate to severe vasomotor symptoms associated with menopause was distinctive for at least two reasons