线程和右值引用

std::thread and rvalue reference

本文关键字:引用 线程      更新时间:2023-10-16

我想有某种委托类。我的方法的缩短版本如下,它的主要功能是启动新线程做一些事情(在这个例子中,它每秒打印文本):

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 );

所以它接受右值reference作为第一个和第二个实参。如果是这样,那么我不应该在将shouldContinue传递给std::thread构造函数后使用它,因为它被移动了

当然我想控制这个函数,因此我想在调用线程中使用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&
}