C ++ Lambda functions may be less efficient than imagined

Source: Internet
Author: User

In C ++ Lambda functions, where are the parameters stored when the function parameters are captured by means of replication?

I thought it was wrong in the stack.

With this question, write a recursive function and name the address of the parameter.

ReferenceCodeAs follows:

# Include <stdio. h> # Include <Functional> Void Fun2 (STD: function < Void ()> Callback) {(callback )();}  Void Fun1 ( Int  N ){  If (N <= 0 ) Return ; Printf (  "  Stack address = % P,  " ,& N); fun2 ([N] () {printf (  "  Capture address = % P \ n  " ,& N); fun1 (n - 1  );});}  Int  Main () {fun1 (  200  ); Return   0  ;} 

(Build Environment: mingw64, version x64-4.8.0-release-posix-seh-rev2)

The results were surprising. The output result is as follows. Note that the address of the capture parameter is notProgramStack region,

And the address is not always continuous.

Obviously, the replication capture parameters expressed by Lambda are dynamically allocated and stored.

Be careful when paying special attention to efficiency or dynamic allocation. Reality is very skinny.

Stack address = 000000000022f1e0, capture address = Destination Address = 000000000022f0c0, capture address = Destination Address = 000000000022efa0, capture address = Destination Address = 000000000022ee80, capture address = Destination Address = 000000000022ed60, capture address = Destination Address = 000000000022ec40, capture address = Destination Address = 000000000022eb20, capture address = Destination Address = 000000000022ea00, capture address = Destination Address = destination, capture address = Destination Address = 000000000022e7c0, capture address = 00000000007a7840

(Reprint please mark: http://www.cnblogs.com/xhawk18)

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.