mercredi 29 août 2018

Is it safe to pass std::function

Given the following working code (main.cpp):

#include <functional>
#include <iostream>

struct worker
{
   std::function<bool(std::string)> m_callback;
   void do_work(std::function<bool(std::string)> callback) // <--- this line
   {
      m_callback = std::bind(callback, std::placeholders::_1);
      callback("hello world!\n");
   }
};


// pretty boring class - a cut down of my actual class
struct helper
{
   worker the_worker;
   bool work_callback(std::string str)
   {
      std::cout << str << std::endl;
      return false;
   }
};

int main()
{
   helper the_helper;
   the_helper.the_worker.do_work( [&](std::string data){ return the_helper.work_callback(data); });
}

Compiled with: -std=c++11 -O2 -Wall -Wextra -pedantic-errors -O2 main.cpp

I have comment the line in question (<-- this line - around line 7), where I think it would be more efficient to use: void do_work(std::function<bool(std::string)>&& callback) i.e. using the && move semantic.

I have never really used this, mostly because I still don't quite understand it.

My understanding is this:

void do_work(std::function<bool(std::string)> callback) - will take a copy of the lambda that I pass in (which is an rvalue I think).

void do_work(std::function<bool(std::string)> callback) - will move the lambda that I pass in because it is an rvalue.

My crude idea of an rvalue is any temporary variable.

Questions:

  1. What I am not 100% clear about is, is what I wrote correct? and therefore is it safe to use &&. Both seem to work.

  2. Does this && method also work if instead of passing a lambda like this:

the_helper.the_worker.do_work( [&](std::string data){ return the_helper.work_callback(data); });

we pass in std::bind(...):

the_worker.do_work(std::bind(&helper::work_callback, the_helper, std::placeholders::_1));

Aucun commentaire:

Enregistrer un commentaire