Are c++11 lambda targets statically created? - c++11

I have a following method:
using async_handler_t = std::function<void(boost::system::error_code, std::size_t)>;
async_handler_t deadlineHandler(boost::system::error_code &ec) {
return [&ec, this](boost::system::error_code newEc, std::size_t) {
ec = newEc;
deadline_.cancel();
};
}
This is simple asio deadline handler which stops the deadline timer and allows the io_service-run loop to continue (grabbed this from official asio timeout docs).
The question is about how much times the function itself is generated. I understand, that I return a functional object from this method (std::function object) which is created dynamically during runtime but is the target function created only once?

The code inside the body of the lambda will only be compiled once and all instances of that lambda's closure object type will share the code. But each call to deadlineHandler will result in a new instance of the closure type being created, its members ec and this being initialised, and then a std::function object being created from that instance.

The lambda expression implicitly declares a functor class, and creates an instance of it.
The generation of the class' type (and the code of its operator()) is, of course, done once at compile-time.
A new instance of this class (containing what the lambda captured) is created each time you call your function.

Related

How to define a member function as a delegate in C++/WinRT

I am trying to define a member function as a delegate for a C++/WinRT component. The component is something that I am trying to build to connect to a BLE device
The idl for the component defines the event as such
event Windows.Foundation.EventHandler<UInt32> ConnectNotification;
In the consuming app I am able to register a delegate for event's if I define it as a lambda function in this fashion
foundBleNotification = m_bleManager.ConnectNotification([](const auto&, uint32_t foundFlags)
{
OutputDebugStringW((L"Lambda Called handler->" + hstring(std::to_wstring(foundFlags)) +L"\r\n").c_str());
});
The above works fine and it gets invoked as expected,
However I would like to try and understand how to use a member function for the delegate instead of a lambda function, based on the idl I assumed I could simply define a member function as so...
void BleFound(uint32_t foundFlags);
And then register the notification by....
foundBleNotification = m_bleManager.ConnectNotification(&MainPage::BleFound };
This results in an error that I just cannot figure out :-(
Error C2511 'void winrt::HelloWorldWinRT::implementation::MainPage::BleFound(const winrt::implements<D,winrt::HelloWorldWinRT::MainPage,winrt::composing,winrt::Windows::UI::Xaml::Controls::IPageOverrides,winrt::Windows::UI::Xaml::Controls::IControlOverrides,winrt::Windows::UI::Xaml::Controls::IControlOverrides6,winrt::Windows::UI::Xaml::IFrameworkElementOverrides,winrt::Windows::UI::Xaml::IFrameworkElementOverrides2,winrt::Windows::UI::Xaml::IUIElementOverrides,winrt::Windows::UI::Xaml::IUIElementOverrides7,winrt::Windows::UI::Xaml::IUIElementOverrides8,winrt::Windows::UI::Xaml::IUIElementOverrides9,winrt::Windows::UI::Xaml::Markup::IComponentConnector,winrt::Windows::UI::Xaml::Markup::IComponentConnector2>::IInspectable &,uint32_t)': overloaded member function not found in 'winrt::HelloWorldWinRT::implementation::MainPage' HelloWorldWinRT C:\Users\Jay\source\repos\HelloWorldWinRT\HelloWorldWinRT\MainPage.cpp 66
I tried reading up on this here
https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/weak-references
But that has me even more confused...
Can some experts please point out what I am doing incorrectly and maybe define a member function that would work per the lambda function?
Thanks!

Are Go methods first class functions?

The title basically says it all..
Can I create a Go method that returns another Go method, at runtime? A simple example:
type Person struct {
name string
age uint
}
func (p Person) createGetNameMethod() /*return signature is a method for Person*/ {
return /*return a new anonymous method here for Person*/
}
Are Go methods first class functions?
Yes, they are.
Can I create a Golang method that returns another Golang method [...]?
Yes, of course.
[Can I] return a new anonymous method [?]
No, of course not.
The set of methods is determined at compile time. Methods are normal, first class functions, but they cannot be changed or created during runtime:
You can return a method that exists in the method set, but you cannot add one to the method set.
Reflection allows something like that but not in your case.

Context of trailing lambda

Below you can see a trailing lambda syntax:
runApplication</*... */>(/*... */) {
setBannerMode(/*... */)
}
I understand the idea that we can pass a lambda outside the parens as a last argument. But what does the code above actually do? setBannerMode is a method that is going to override the one in the parent class, isn't it? If yes, what class is the parent one? Is there some this context between the braces of the trailing lambda? In general, what's happening there?
the code is from here
setBannerMode is a method that is being overriden, isn't it?
No. What you are doing is passing a lambda to runApplication() that has a this implicit receiver .
Here is the definition (Spring documentation):
inline fun <reified T : Any> runApplication(vararg args: String, init: SpringApplication.() -> Unit): ConfigurableApplicationContext =
SpringApplication(T::class.java).apply(init).run(*args)
The init: SpringApplication.() -> Unit here is the definition of the lambda with implicit receiver. It means that inside the lambda, this will be a SpringApplication.
To break it down:
SpringApplication(T::class.java) - create a new spring application. T is calculated from the calling context by the Kotlin compiler (that's what reified T means).
apply(init). Calls your lambda (init), with the SpringApplication as the receiver (Kotlin docs for apply).
Call the SpringApplication's run() function with the varargs arguments. This function returns a ConfigurableApplicationContext.
So, you are calling the setBannerMode() method of the instantiated SpringApplication object.

Is a capture captured even if it isn't used?

I'm using an async function that takes an object reference &foo and a callback cb as arguments. I want to prevent destruction of foo until the callback is called.
void async_thing(Foo &foo, function<void()> cb) {
// do something asynchronously with foo
}
Is it enough to simply capture it in the callback lambda? Or does it need to be actually used in the lambda?
auto foo = make_shared<Foo>();
async_thing(*foo, [foo]() {
cout << "Callback ran" << endl;
});
Might a compiler optimise the capture out, and delete foo prematurely?
n3690, section 5.1.2
15.
An entity is captured by copy if it is implicitly captured and the
capture-default is = or if it is explicitly captured with a capture
that does not include an &. For each entity captured by copy, an
unnamed nonstatic data member is declared in the closure type.
Above which we have:
3.
The type of the lambda-expression (which is also the type of the
closure object) is a unique, unnamed nonunion class type — called the
closure type.
[…]
An implementation may define the closure type
differently from what is described below provided this does not alter
the observable behavior of the program other than by changing:
the size and/or alignment of the closure type,
whether the closure type is trivially copyable (Clause 9),
whether the closure type is a standard-layout class (Clause 9), or
whether the closure type is a POD class (Clause 9).
From this I would conclude that:
The capture makes a shared_ptr member in the closure type.
The compiler is not allowed to alter that observable behavior.
So your pointer won't be deleted until the destructor of the closure is called.

Why use spyOn instead of jasmine.createSpy?

What is the difference between
jasmine.createSpy('someMethod')
And
spyOn(someObject, 'someMethod')
And why should one choose to use spyOn?
My guess is that the first alternative will match the method someMethod no matter in what object it's contained but spyOn will only match if it's contained in someObject. Thus making createSpy just a more generic matcher?
The difference is that you should have a method on the object with spyOn
const o = { some(): { console.log('spied') } };
spyOn(o, 'some');
while the mock method is created for your with createSpy():
const o = {};
o.some = jasmine.createSpy('some');
The advantage of the spyOn is that you can call the original method:
spyOn(o, 'some').and.callThrough();
o.some(); // logs 'spied'
And as #estus says the original method is restored after the test in case of spyOn. This should be done manually when it's reassigned with.
Additionally to the other fine answer:
Use spyOn() to spy (intercept) an existing method on an object to track calls of other modules to it.
Use jasmine.createSpy() to create a function that can be passed as callback or Promise handler to track call-backs.

Resources