繁体   English   中英

`std::thread` object 的构造函数中的 `decay_copy` 有什么作用?

[英]What does `decay_copy` in the constructor in a `std::thread` object do?

我试图理解std::thread的构造函数,但无法理解参数类型是如何表示/处理的。 cppreference来看,一个简化的构造函数可以绘制如下:

class thread {
   public:
    template <class Function, class Arg>
    thread(Function&& f, Arg&& arg) {
        // something happening
        std::invoke(decay_copy(std::forward<Function>(f)),
                    decay_copy(std::forward<Arg>(arg)));
        // something else happening
    }
};

cppreference 将decay_copy定义为:

template <class T>
std::decay_t<T> decay_copy(T&& v) { return std::forward<T>(v); }

我对以下示例进行了一些实验:

struct X{};
int main() {
    X x1{};
    X& x2 = x1;
    auto f = []() { return; };
    thread t1{f, x1}; // arg should be of type X& after the inner std::forward<Arg>(arg);
    thread t2{f, x2}; // arg should be of type X& after the inner std::forward<Arg>(arg);
    thread t3{f, X{}}; // arg should be of type X&& after the inner std::forward<Arg>(arg);
}

根据我的分析, x1x2在内部std::forward之后都是左值引用类型,而X{}是右值引用类型。 我相信我们需要以某种方式将x1x2分开以通过值或引用传递它。 分析让我想到三个问题:

  • 上面的分析正确吗?
  • decay_copy如何正确解开类型?
  • 在开始了一段时间之后,我想:哦,麻烦,为什么会这么复杂? 可以更轻松地完成吗? 答案当然是否定的,但我对整个操作仍然缺乏直觉。

我很感激任何提示、建议或解释!

标准线程复制(或移动)到 arguments 类型的衰减版本。 衰减的版本既不是引用也不是 const 也不是 volatile 也不是数组(数组和函数成为指针)。

如果您想要一个左值引用参数,请使用引用包装器。 否则线程ctor中被调用的function会得到一个右值; 衰减副本仅确定您在线程 function 中传递的右值是如何从您的 std 线程参数构造的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM