我在尝试创建使用C ++ 11标准线程的VC ++静态库时遇到问题。
我目前有两个类,我可以声明并稍后在我的起始类(最后声明)上定义一个线程。在这个阶段,代码只是一个套接字侦听器,然后它创建另一个类的对象来处理每个接受的客户端。这些子对象应该创建我需要用于并行数据捕获,编码和传输的线程。
问题是:如果我在另一个类上声明了一个std :: thread,即使与我在开始类上所做的完全一样,无论如何,我在构建时会遇到此错误 error C2280: 'std::thread::thread(const std::thread &)' : attempting to reference a deleted function [...]\vc\include\functional 1124 1
我能够解决此错误的唯一方法是std::thread
,根据我想要的操作,根本就不要在后一个类中声明一个对象,这是不可能的...
我正在使用VS2013,我的来源是:
stdafx.h
#pragma once
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <Windows.h>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <thread>
#include <iostream>
#include <vector>
StreamServer.h
#pragma once
#define DEFAULT_BUFLEN 65535
#define DEFAULT_PORT "5649"
class StreamServerClient
{
public:
bool* terminate;
//std::thread client; //If I comment this line out, it builds just fine.
void DoNothing();
StreamServerClient(SOCKET clientSock, bool* ptTerm);
StreamServerClient();
~StreamServerClient();
};
class StreamServer
{
public:
bool terminate;
std::thread Listener;
std::vector<StreamServerClient> clients;
void CreateClient(SOCKET, bool*);
void Listen();
StreamServer();
~StreamServer();
};
StreamServer.cpp
#include "stdafx.h"
#include "StreamServer.h"
StreamServerClient::StreamServerClient(SOCKET clientSock, bool* ptTerm)
{
terminate = ptTerm;
//client = std::thread(&StreamServerClient::DoNothing, this); //Same thing as the declaration
}
StreamServerClient::StreamServerClient()
{
*terminate = false;
//client = std::thread(&StreamServerClient::DoNothing, this); //Same thing as the declaration
}
void StreamServerClient::DoNothing()
{
}
StreamServerClient::~StreamServerClient()
{
}
void StreamServer::Listen()
{
{...}
do {
clients.push_back(StreamServerClient::StreamServerClient(accept(listenSock, NULL, NULL), &terminate));
std::cout << "accepted a client!" << std::endl;
} while (!terminate);
}
StreamServer::StreamServer()
{
terminate = false;
Listener = std::thread(&StreamServer::Listen, this);
Listener.detach();
}
StreamServer::~StreamServer()
{
}
类型的对象std::thread
无法复制。最好只初始化成员初始化器列表中的对象:
class StreamServerClient
{
public:
bool* terminate;
std::thread client;
void DoNothing();
StreamServerClient(SOCKET clientSock, bool* ptTerm);
StreamServerClient(StreamServerClient&& other);
~StreamServerClient();
};
StreamServerClient::StreamServerClient(SOCKET clientSock, bool* ptTerm)
: terminate(ptTerm)
, client(std::thread(&StreamServerClient::DoNothing, this)) {
}
StreamServerClient::StreamServerClient(StreamServerClient&& other)
: terminate(other.terminate)
, client(std::move(other.client)) {
}
我省略了默认构造函数(请注意,您的版本无法正常工作,因为它试图为取消引用未初始化的指针的结果分配一个值),而是添加了move构造函数:当推回std::vector<...>
this构造函数时,会在提供某些内容时调用它看起来像是临时的(即,某些东西是临时的,或者看起来像是一个临时的东西,例如使用std::move()
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句