我想要某种委托(delegate)类。我的方法的简化版本如下,它的主要功能是启动新线程做一些事情(在这个例子中它每秒打印一次文本):
void Flusher::start(){
m_continue.store(true);
m_thread = std::thread([](std::atomic<bool>& shouldContinue){
while(shouldContinue.load()){
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "sec passed" << std::endl;
}}, std::ref<std::atomic<bool>>(m_continue)
);
}
我担心的是,std::thread 构造函数具有以下签名:
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
因此它将右值引用作为第一个和第二个参数。如果是这样,那么我不应该在将它传递给 std::thread
构造函数后使用 shouldContinue
,因为它已被移动。
当然我想控制这个函数,因此我想在调用者线程中使用 shouldContinue 来停止被调用的函数。出于显而易见的原因,我不想将此变量设为全局变量。
我认为 std::ref
在那里发挥了一些魔力,但我仍然不确定它是如何工作的(我在一些示例中看到了 std::ref
创建新线程时)。
我试图完全不关心这个事实,这是右值引用,后来我使用了 shouldContinue
并且没有崩溃,但我担心这只是未定义的行为。谁能告诉上面的代码是否正确,如果不正确,如何正确执行此操作?
最佳答案
当 && 与模板一起使用时,有一个特殊的类型推导规则。
检查这个以获得一个非常好的解释:
http://eli.thegreenplace.net/2014/perfect-forwarding-and-universal-references-in-c/
template <class T>
void func(T&& t) {
}
“当&&出现在类型推导上下文中时,T&&获得了特殊的含义。当func被实例化时,T取决于传递给func的参数是左值还是右值。如果是U类型的左值,T推导为 U&。如果它是右值,则 T 推导为 U:"
func(4); // 4 is an rvalue: T deduced to int
double d = 3.14;
func(d); // d is an lvalue; T deduced to double&
float f() {...}
func(f()); // f() is an rvalue; T deduced to float
int bar(int i) {
func(i); // i is an lvalue; T deduced to int&
}
另外,引用折叠规则是一本好书。
关于c++ - std::thread 和右值引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32809192/