C++ 11矢量STD的线程::
我试图让std::thread
的vector
秒。我可以结合以下三点。
1)根据http://en.cppreference.com/w/cpp/thread/thread/thread, thread
的默认构造函数创建一个
thread object which does not represent a thread.
2.)根据http://en.cppreference.com/w/cpp/thread/thread/operator%3D,thread
的operator=
Assigns the state of [the parameter, which is a thread rvalue reference] to [the calling thread] using move semantics.
3.)根据 http://en.cppreference.com/w/cpp/container/vector/vector,将 只有一个尺寸类型的变量传递给一个向量构造函数将解析CT
the container with [the specified number of] value-initialized (default constructed, for classes) instances of T. No copies are made.
所以,我这样做:
#include <iostream>
#include <thread>
#include <vector>
void foo()
{
std::cout << "Hello\n";
return;
}
int main()
{
std::vector<std::thread> vecThread(1);
vecThread.at(0) = std::thread(foo);
vecThread.at(0).join();
return 0;
}
这运行正常的VC11和g++ 4.8.0 (online compiler here)如下面所示:
控制台输出:
Hello
然后我试图它在铛3.2,通过切换在同一网页上,这给编译器菜单:
stderr:
pure virtual method called
terminate called without an active exception
当一个线程对象表示一个线程超出范围是join()
ED或detach()
之前该程序将被迫终止。我有join()
版vecThread.at(0)
,所以留在问题的唯一事情是临时线程
std::thread(foo);
在
vecThread.at(0) = std::thread(foo);
分配。
但是,根据Web引用,只能通过移动线程右值引用来分配线程。我想不出任何方法来join()
或detach()
一个临时线程对象。
所以如果铿锵的输出是正确的,那么thread
的operator=
有什么用?或者这是一个铿锵编译器错误?
In g ++ 4.8。0,改变线
vecThread.at(0) = std::thread(foo)
到
vecThread.at(0) = std::thread{foo}
(用大括号替换括号内)仍然给出了预期Hello
输出。
然而,转产到vecThread.at(0) = {foo}
使得抱怨:
G ++ 4.8.0对大括号投诉:
error: converting to 'std::thread' from initializer list would use explicit constructor 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(); _Args = {}]' vecThread.at(0) = {foo};
是太先进了,我不知道这意味着什么。
使在铛相同的变化给出了更先进:
铛3.2的牙齿矫正器上抱怨:
error: no viable overloaded '='
vecThread.at(0) = {foo};
...
note: candidate function not viable: cannot convert initializer list
argument to 'const std::thread'
thread& operator=(const thread&) = delete;
...
note: candidate function not viable: cannot convert initializer list
argument to 'std::thread'
thread& operator=(thread&& __t) noexcept
,我不知道是什么意思要么。
我不能使用VC11,以证实上述
vecThread.at(0) = {foo}
问题,因为VC11,为2012年11月CTP编译器,不支持标准库的统一初始化语法。
你用'-pthread'编译了吗?代码看起来很好,尽管有点冗长。 – 2013-03-16 04:24:08
你的意思是我应该在编译器的'compiler/interpreter'参数文本字段中添加'-pthread'?我将它添加到网页的文本字段的原始编译器/解释器参数中,使其在叮当声中成为'-std = C++ 11 -Wall -W -pedantic -O2 -pthread',但获得与'terminate'被调用相同的结果。 – CodeBricks 2013-03-16 04:43:02
那么,[编码](http://ideone.com/4B2Elt)适用于编译时用'-std = C++ 0x -pthread' ... – 2013-03-16 04:46:43