I have the following (contrived) code where I have a printer class with a single print function in it and a working class that processes a string and then calls a callback function to the print function:
#include <functional>
#include <iostream>
using callback_fn = std::function<bool(std::string)>;
class printer
{
public:
bool print(std::string data)
{
std::cout << data << std::endl;
return true;
}
};
class worker
{
public:
callback_fn m_callback;
void set_callback(callback_fn callback)
{
m_callback = std::move(callback); // <-- 1. callback is a temp, so what does std::move do here?
}
void process_data(std::string data)
{
if (!m_callback(data)) { /* do error handling */ }
}
};
int main() {
printer p;
worker w;
w.set_callback( std::move([&](std::string s){ return p.print(s); }) ); // <-- 2. what does std::move do here?
w.process_data("hello world2");
}
Note: I have std:: move()
called twice... now this works (surprisingly to me) but I have both only to show what I am trying. My questions are:
- Should I use
std::move()
in theset_callback()
function to "pull" out the temp, and if I use this is there really a copy or doesstd:: move(
) mean that its not really a copy? - Should I use
std:: move()
to pass in the lambda... and is that even correct. - I guess I don't understand why this code works with two
std:: moves()
... which implies that I still don't understand whatstd:: move()
is doing - so if someone can elighten me on what is going on here that would be great! - I know that I can pass by value, but my goal is to move the temp so that I don't have a copy of it. Is that what is meant by perfect forwarding?
My example can be seen here in wandbox: https://wandbox.org/permlink/rJDudtg602Ybhnzi
UPDATE The reason for me trying to use std::move was to avoid copying the lambda around. (I think that is called forwarding/perfect-forwarding)...but I think I am making a hash of it!