以下程序不在 VS11 beta、gcc 4.5 或 clang 3.1 中构建
#include <thread>
#include <memory>
int main() {
std::unique_ptr<int> p;
std::thread th([](std::unique_ptr<int>) {
},std::move(p));
th.join();
}
这是因为参数类型不可复制,但实现试图复制它。
据我所知,这个程序格式正确,应该可以运行。 std::thread 的要求似乎暗示可移动的、不可复制的参数应该在这里起作用。具体来说,它表示可调用对象和每个参数应满足 MoveConstructible 要求,并且 INVOKE(DECAY_COPY(std::forward<F>(f)),DECAY_COPY(std::forward<Args>(args))...)
应为有效表达式。
在这种情况下,我认为表达式的结果类似于:
template <class T> typename std::decay<T>::type decay_copy(T&& v)
{ return std::forward<T>(v); }
std::unique_ptr<int> p;
auto f = [](std::unique_ptr<int>) {};
decay_copy(f)(decay_copy(std::move(p)));
而且我认为这不应该涉及 p
的拷贝. gcc 至少可以编译这个表达式,尽管 VS11 不能。
- 我对要求和参数必须是可复制的有误吗?
- 标准是否在这个问题上为实现复制参数留有余地?
- 或者我尝试的实现不符合要求?
最佳答案
来自 30.3.1.2,N3337 的第 3 段和第 4 段:
template <class F, class ...Args> explicit thread(F&& f, Args&&... args);
Requires:
F
and eachTi
inArgs
shall satisfy theMoveConstructible
requirements.INVOKE (DECAY_-COPY ( std::forward<F>(f)), DECAY_COPY (std::forward<Args>(args))...)
(20.8.2) shall be a valid expression.Effects: Constructs an object of type thread. The new thread of execution executes
INVOKE (DECAY_-COPY ( std::forward<F>(f)), DECAY_COPY (std::forward<Args>(args))...)
with the calls toDECAY_COPY
being evaluated in the constructing thread. Any return value from this invocation is ignored. [ Note: This implies that any exceptions not thrown from the invocation of the copy off
will be thrown in the constructing thread, not the new thread. —end note ] If the invocation ofINVOKE (DECAY_COPY ( std::forward<F>(f)), DECAY_COPY (std::forward<Args>(args))...)
terminates with an uncaught exception, std::terminate shall be called.
所以是的,这应该有效。如果不是,则说明您的实现存在错误。
请注意,任何参数移动/复制都将在新线程上发生。您正在将引用传递给另一个线程,因此您需要确保在该线程启动之前它们仍然存在。
关于c++ - 带有可移动、不可复制参数的 std::thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10001751/