我正在做一個簡單的服務器應用程序,你可以有多個連接,每個連接是一個單一的線程。這是我想它看起來像(它不工作)的例子中,有線程的集合,每個線程實例化類連接物:C++對象和線程
class connection{};
class server{
std::vector<std::thread> active_connections;
public:
void listen() {active_connections.push_back(std::thread(connection));}
};
我一直在尋找解決方案,但我能找到的最好的是一些成員函數線程。溶液變成非常錯誤的,當我測試它,例如:
class connection{};
class server{
std::vector<std::thread> active_connections;
public:
void new_connection() { ... }
void listen() {
active_connections.push_back(std::thread(&server::new_connection,this)); }
};
的信息是:錯誤:使用刪除功能「的std ::螺紋::線程(常量的std ::線程&)的。 這是否意味着std :: thread類想要複製服務器類?我不太瞭解C++,所以請不要燃燒,我只是問。
謝謝!
編輯:
這是發生這種情況:
void server::do_listen()
{
int addr_size = sizeof(sockaddr_in);
sockaddr_in client_sock;
connection_info cn_info;
while(true)
{
int csock;
if((csock = accept(server_sock, (sockaddr*)&client_sock, (socklen_t*)&addr_size)) != -1)
{
printf("Incomming connection from %s.\n", inet_ntoa(client_sock.sin_addr));
memset(&cn_info,0, sizeof(connection_info));
cn_info.sock_addr = client_sock;
cn_info.sock = csock;
std::thread thr(&server::new_connection, *this, cn_info);
thr.join();
}
}
}
這是迄今爲止。 server::new_connection()
仍然是空的。
可能的重複[Error C2280:'std :: thread :: thread(const std :: thread&)':試圖引用已刪除的函數](http://stackoverflow.com/questions/20723566/error- c2280-stdthreadthreadconst-stdthread-attempting-to-reference) – duDE 2014-09-05 12:20:38
這意味着某事正試圖複製一個不可複製的'thread'對象。但是你發佈的代碼並沒有這樣做,並且一旦我修復了顯而易見的錯誤('active_connections'應該是一個變量,而不是一個函數)就會編譯。請發佈一個最簡單的測試用例,演示您遇到的問題。 – 2014-09-05 12:22:16