0

I have some questions

  1. Where is the memory location of the C++ lambda's code and captured variable?

  2. when lambda's memory be free? (condition)

  3. "std::function::operator=()" copy code or code's pointer?

  4. is there any deep copy method for std::function?

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
damhiya
  • 473
  • 3
  • 7

1 Answers1

1

Lambda expression is just a convenient shorthand for creating a temporary functional object (and defining its corresponding class). The object simply contains the captured values as its immediate data members. In that regard, lambdas do not really introduce anything qualitatively new into the language.

The lifetime of the lambda object would be the same if you declared the class explicitly and created that temporary functional object manually. Its "memory" is located wherever memory for any other temporaries is located. The language does define where it is. Such objects are destroyed in accordance with the same rules all other temporary objects are destroyed, i.e. they are automatically destroyed at the end of full expression (aside from those exceptional situations where lifetime of a temporary gets extended).

There's no concept of "copying the code" in C++. std::function object simply uses an implementation-specific technique of storing the functor it was initialized with (functional objects, including lambdas, regular function pointers, member function pointers) in combination with some unspecified type-erasure technique. There's no need to "copy the code" for that.

It is not clear what you mean by "deep copy" for std::function object. The interface specification of that class does not provide for any distinction between deep and shallow copying.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • "deep copy" was mean "copy the code into another memory location" ps. I'm sorry for my terrible english skill... – damhiya Sep 30 '16 at 06:57
  • @SoonwonMoon In C++ "code" is something completely immutable that lives somewhere in special "code" storage. Since it is immutable, there's never any need to copy code: whoever needs it just uses the same "copy" of it. – AnT stands with Russia Sep 30 '16 at 15:00