c++ - 传递 std::function<bool(std::string)> &&callback(即作为右值 move )是否安全,效果如何?

标签 c++ c++11 move-semantics rvalue-reference

给定以下工作代码 (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); });
}

编译:-std=c++11 -O2 -Wall -Wextra -pedantic-errors -O2 main.cpp

我对有问题的行(<-- this line - 大约第 7 行)进行了评论,我认为使用它会更有效率:void do_work(std::function<bool(std::string)>&& callback)即使用 && move 语义。

我从来没有真正使用过这个,主要是因为我还是不太明白。

我的理解是这样的:

void do_work(std::function<bool(std::string)> callback) - 将获取我传入的 lambda 的拷贝(我认为这是一个右值)。

void do_work(std::function<bool(std::string)> callback) - 将 move 我传入的 lambda,因为它是一个右值。

我对右值的粗略想法是任何临时变量。

问题:

  1. 我不是 100% 清楚的是,我写的是否正确?因此使用 && 安全吗? .两者似乎都有效。

  2. 这是&&吗?如果不是像这样传递 lambda,该方法也有效:

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

我们传入 std::bind(...):

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

最佳答案

如果参数被定义为右值引用,则必须传递一个临时值或将左值转换为右值,就像 std::move() 一样。

右值引用的语义是调用者应该期望传递的参数被掠夺,使其有效但任意,这意味着大部分无用。

但是接收右值引用的函数,尽管有掠夺许可,但没有任何掠夺义务。如果它没有明确这样做,例如通过传递该许可证,那么它就不会通过,也不会发生任何特殊情况。

你的代码就是这种情况。

虽然我会从我的词汇表中禁止 std::bind,但使用与否实际上没有任何显着差异。

关于c++ - 传递 std::function<bool(std::string)> &&callback(即作为右值 move )是否安全,效果如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52075259/

相关文章:

c++ - 将左值引用 move 到成员变量中

c++ - C++中的临时对象在哪里分配?

c++ - 信件取出

c++ - 错误 C2146 : syntax error : missing ';' before identifier 'ContextRecord'

c++ - 在 constexpr 构造函数中复制数组

c++11 - 递归变量声明

c++ - 为什么 std::move 采用 forward_reference 而不是 lvaue 引用

无法识别 C++ 多个函数

c++ - map<string, string[]> 在 C++ 中可能吗?

C++ - 直接插入 std::map 而不使用赋值运算符