给定以下工作代码 (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,因为它是一个右值。
我对右值的粗略想法是任何临时变量。
问题:
我不是 100% 清楚的是,我写的是否正确?因此使用
&&
安全吗? .两者似乎都有效。这是
&&
吗?如果不是像这样传递 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/