Use std::make_shared and make_unique where possible, part 2

pull/287/head
Tatsuhiro Tsujikawa 2014-09-13 18:37:57 +09:00
parent 596e5c6162
commit 9b84727324
49 changed files with 140 additions and 173 deletions

View File

@ -95,13 +95,9 @@ std::unique_ptr<Command> HttpInitiateConnectionCommand::createNextCommand
getDownloadEngine(), getDownloadEngine(),
getSocket()); getSocket());
if(proxyMethod == V_TUNNEL) { if(proxyMethod == V_TUNNEL) {
std::shared_ptr<HttpProxyRequestConnectChain> chain c->setControlChain(std::make_shared<HttpProxyRequestConnectChain>());
(new HttpProxyRequestConnectChain());
c->setControlChain(chain);
} else if(proxyMethod == V_GET) { } else if(proxyMethod == V_GET) {
std::shared_ptr<HttpRequestConnectChain> chain c->setControlChain(std::make_shared<HttpRequestConnectChain>());
(new HttpRequestConnectChain());
c->setControlChain(chain);
} else { } else {
// Unreachable // Unreachable
assert(0); assert(0);
@ -110,15 +106,14 @@ std::unique_ptr<Command> HttpInitiateConnectionCommand::createNextCommand
return std::move(c); return std::move(c);
} else { } else {
setConnectedAddrInfo(getRequest(), hostname, pooledSocket); setConnectedAddrInfo(getRequest(), hostname, pooledSocket);
std::shared_ptr<SocketRecvBuffer> socketRecvBuffer auto c = make_unique<HttpRequestCommand>
(new SocketRecvBuffer(pooledSocket)); (getCuid(),
std::shared_ptr<HttpConnection> httpConnection
(new HttpConnection(getCuid(), pooledSocket, socketRecvBuffer));
auto c = make_unique<HttpRequestCommand>(getCuid(),
getRequest(), getRequest(),
getFileEntry(), getFileEntry(),
getRequestGroup(), getRequestGroup(),
httpConnection, std::make_shared<HttpConnection>
(getCuid(), pooledSocket,
std::make_shared<SocketRecvBuffer>(pooledSocket)),
getDownloadEngine(), getDownloadEngine(),
pooledSocket); pooledSocket);
if(proxyMethod == V_GET) { if(proxyMethod == V_GET) {
@ -144,24 +139,21 @@ std::unique_ptr<Command> HttpInitiateConnectionCommand::createNextCommand
getRequestGroup(), getRequestGroup(),
getDownloadEngine(), getDownloadEngine(),
getSocket()); getSocket());
std::shared_ptr<HttpRequestConnectChain> chain c->setControlChain(std::make_shared<HttpRequestConnectChain>());
(new HttpRequestConnectChain());
c->setControlChain(chain);
setupBackupConnection(hostname, addr, port, c.get()); setupBackupConnection(hostname, addr, port, c.get());
return std::move(c); return std::move(c);
} else { } else {
setSocket(pooledSocket); setSocket(pooledSocket);
setConnectedAddrInfo(getRequest(), hostname, pooledSocket); setConnectedAddrInfo(getRequest(), hostname, pooledSocket);
std::shared_ptr<SocketRecvBuffer> socketRecvBuffer return make_unique<HttpRequestCommand>
(new SocketRecvBuffer(getSocket())); (getCuid(),
std::shared_ptr<HttpConnection> httpConnection
(new HttpConnection(getCuid(), getSocket(), socketRecvBuffer));
return make_unique<HttpRequestCommand>(getCuid(),
getRequest(), getRequest(),
getFileEntry(), getFileEntry(),
getRequestGroup(), getRequestGroup(),
httpConnection, std::make_shared<HttpConnection>
(getCuid(), getSocket(),
std::make_shared<SocketRecvBuffer>(getSocket())),
getDownloadEngine(), getDownloadEngine(),
getSocket()); getSocket());
} }

View File

@ -96,7 +96,7 @@ bool HttpListenCommand::bindPort(uint16_t port)
if(serverSocket_) { if(serverSocket_) {
e_->deleteSocketForReadCheck(serverSocket_, this); e_->deleteSocketForReadCheck(serverSocket_, this);
} }
serverSocket_.reset(new SocketCore()); serverSocket_ = std::make_shared<SocketCore>();
const int ipv = (family_ == AF_INET) ? 4 : 6; const int ipv = (family_ == AF_INET) ? 4 : 6;
try { try {
int flags = 0; int flags = 0;

View File

@ -62,7 +62,7 @@ std::unique_ptr<util::security::HMAC> HttpServer::hmac_;
HttpServer::HttpServer(const std::shared_ptr<SocketCore>& socket) HttpServer::HttpServer(const std::shared_ptr<SocketCore>& socket)
: socket_(socket), : socket_(socket),
socketRecvBuffer_(new SocketRecvBuffer(socket_)), socketRecvBuffer_(std::make_shared<SocketRecvBuffer>(socket_)),
socketBuffer_(socket), socketBuffer_(socket),
headerProcessor_(make_unique<HttpHeaderProcessor> headerProcessor_(make_unique<HttpHeaderProcessor>
(HttpHeaderProcessor::SERVER_PARSER)), (HttpHeaderProcessor::SERVER_PARSER)),
@ -341,7 +341,7 @@ int HttpServer::setupResponseRecv()
if(path == "/jsonrpc") { if(path == "/jsonrpc") {
if(reqType_ != RPC_TYPE_JSON) { if(reqType_ != RPC_TYPE_JSON) {
reqType_ = RPC_TYPE_JSON; reqType_ = RPC_TYPE_JSON;
lastBody_.reset(new json::JsonDiskWriter()); lastBody_ = make_unique<json::JsonDiskWriter>();
} }
return 0; return 0;
} }
@ -349,7 +349,7 @@ int HttpServer::setupResponseRecv()
if(path == "/rpc") { if(path == "/rpc") {
if(reqType_ != RPC_TYPE_XML) { if(reqType_ != RPC_TYPE_XML) {
reqType_ = RPC_TYPE_XML; reqType_ = RPC_TYPE_XML;
lastBody_.reset(new rpc::XmlRpcDiskWriter()); lastBody_ = make_unique<rpc::XmlRpcDiskWriter>();
} }
return 0; return 0;
} }

View File

@ -67,7 +67,7 @@ HttpServerCommand::HttpServerCommand
: Command(cuid), : Command(cuid),
e_(e), e_(e),
socket_(socket), socket_(socket),
httpServer_(new HttpServer(socket)), httpServer_(std::make_shared<HttpServer>(socket)),
writeCheck_(false) writeCheck_(false)
{ {
setStatus(Command::STATUS_ONESHOT_REALTIME); setStatus(Command::STATUS_ONESHOT_REALTIME);

View File

@ -147,7 +147,7 @@ InitiateConnectionCommand::createBackupIPv4ConnectCommand
for(std::vector<std::string>::const_iterator i = addrs.begin(), for(std::vector<std::string>::const_iterator i = addrs.begin(),
eoi = addrs.end(); i != eoi; ++i) { eoi = addrs.end(); i != eoi; ++i) {
if(inetPton(AF_INET, (*i).c_str(), &buf) == 0) { if(inetPton(AF_INET, (*i).c_str(), &buf) == 0) {
info.reset(new BackupConnectInfo()); info = std::make_shared<BackupConnectInfo>();
auto command = make_unique<BackupIPv4ConnectCommand> auto command = make_unique<BackupIPv4ConnectCommand>
(getDownloadEngine()->newCUID(), *i, port, info, mainCommand, (getDownloadEngine()->newCUID(), *i, port, info, mainCommand,
getRequestGroup(), getDownloadEngine()); getRequestGroup(), getDownloadEngine());

View File

@ -70,7 +70,7 @@ InitiatorMSEHandshakeCommand::InitiatorMSEHandshakeCommand
requestGroup_(requestGroup), requestGroup_(requestGroup),
btRuntime_(btRuntime), btRuntime_(btRuntime),
sequence_(INITIATOR_SEND_KEY), sequence_(INITIATOR_SEND_KEY),
mseHandshake_(new MSEHandshake(cuid, s, getOption().get())) mseHandshake_(make_unique<MSEHandshake>(cuid, s, getOption().get()))
{ {
disableReadCheckSocket(); disableReadCheckSocket();
setWriteCheckSocket(getSocket()); setWriteCheckSocket(getSocket());
@ -84,8 +84,6 @@ InitiatorMSEHandshakeCommand::~InitiatorMSEHandshakeCommand()
{ {
requestGroup_->decreaseNumCommand(); requestGroup_->decreaseNumCommand();
btRuntime_->decreaseConnections(); btRuntime_->decreaseConnections();
delete mseHandshake_;
} }
bool InitiatorMSEHandshakeCommand::executeInternal() { bool InitiatorMSEHandshakeCommand::executeInternal() {

View File

@ -67,7 +67,7 @@ private:
std::shared_ptr<BtRuntime> btRuntime_; std::shared_ptr<BtRuntime> btRuntime_;
Seq sequence_; Seq sequence_;
MSEHandshake* mseHandshake_; std::unique_ptr<MSEHandshake> mseHandshake_;
const std::shared_ptr<Option>& getOption() const; const std::shared_ptr<Option>& getOption() const;

View File

@ -58,7 +58,7 @@ IteratableChunkChecksumValidator::IteratableChunkChecksumValidator
const std::shared_ptr<PieceStorage>& pieceStorage) const std::shared_ptr<PieceStorage>& pieceStorage)
: dctx_(dctx), : dctx_(dctx),
pieceStorage_(pieceStorage), pieceStorage_(pieceStorage),
bitfield_(new BitfieldMan(dctx_->getPieceLength(), bitfield_(make_unique<BitfieldMan>(dctx_->getPieceLength(),
dctx_->getTotalLength())), dctx_->getTotalLength())),
currentIndex_(0) currentIndex_(0)
{} {}

View File

@ -52,7 +52,7 @@ class IteratableChunkChecksumValidator:public IteratableValidator
private: private:
std::shared_ptr<DownloadContext> dctx_; std::shared_ptr<DownloadContext> dctx_;
std::shared_ptr<PieceStorage> pieceStorage_; std::shared_ptr<PieceStorage> pieceStorage_;
std::shared_ptr<BitfieldMan> bitfield_; std::unique_ptr<BitfieldMan> bitfield_;
size_t currentIndex_; size_t currentIndex_;
std::unique_ptr<MessageDigest> ctx_; std::unique_ptr<MessageDigest> ctx_;

View File

@ -280,8 +280,6 @@ bool KqueueEventPoll::addNameResolver
bool KqueueEventPoll::deleteNameResolver bool KqueueEventPoll::deleteNameResolver
(const std::shared_ptr<AsyncNameResolver>& resolver, Command* command) (const std::shared_ptr<AsyncNameResolver>& resolver, Command* command)
{ {
std::shared_ptr<KAsyncNameResolverEntry> entry
(new KAsyncNameResolverEntry(resolver, command));
auto key = std::make_pair(resolver.get(), command); auto key = std::make_pair(resolver.get(), command);
auto itr = nameResolverEntries_.find(key); auto itr = nameResolverEntries_.find(key);
if(itr == std::end(nameResolverEntries_)) { if(itr == std::end(nameResolverEntries_)) {

View File

@ -108,7 +108,7 @@ typedef MessageDigestBase<GCRY_MD_SHA512> MessageDigestSHA512;
std::unique_ptr<MessageDigestImpl> MessageDigestImpl::sha1() std::unique_ptr<MessageDigestImpl> MessageDigestImpl::sha1()
{ {
return std::unique_ptr<MessageDigestImpl>(new MessageDigestSHA1()); return make_unique<MessageDigestSHA1>();
} }
MessageDigestImpl::hashes_t MessageDigestImpl::hashes = { MessageDigestImpl::hashes_t MessageDigestImpl::hashes = {

View File

@ -45,7 +45,7 @@ namespace {
template<const nettle_hash* hash> template<const nettle_hash* hash>
class MessageDigestBase : public MessageDigestImpl { class MessageDigestBase : public MessageDigestImpl {
public: public:
MessageDigestBase() : ctx_(new char[hash->context_size]) { MessageDigestBase() : ctx_(make_unique<char[]>(hash->context_size)) {
reset(); reset();
} }
virtual ~MessageDigestBase() {} virtual ~MessageDigestBase() {}
@ -87,7 +87,7 @@ typedef MessageDigestBase<&nettle_sha512> MessageDigestSHA512;
std::unique_ptr<MessageDigestImpl> MessageDigestImpl::sha1() std::unique_ptr<MessageDigestImpl> MessageDigestImpl::sha1()
{ {
return std::unique_ptr<MessageDigestImpl>(new MessageDigestSHA1()); return make_unique<MessageDigestSHA1>();
} }
MessageDigestImpl::hashes_t MessageDigestImpl::hashes = { MessageDigestImpl::hashes_t MessageDigestImpl::hashes = {

View File

@ -86,7 +86,7 @@ typedef MessageDigestBase<EVP_sha1> MessageDigestSHA1;
std::unique_ptr<MessageDigestImpl> MessageDigestImpl::sha1() std::unique_ptr<MessageDigestImpl> MessageDigestImpl::sha1()
{ {
return std::unique_ptr<MessageDigestImpl>(new MessageDigestSHA1()); return make_unique<MessageDigestSHA1>();
} }
MessageDigestImpl::hashes_t MessageDigestImpl::hashes = { MessageDigestImpl::hashes_t MessageDigestImpl::hashes = {

View File

@ -94,7 +94,7 @@ void LogFactory::reconfigure()
const std::shared_ptr<Logger>& LogFactory::getInstance() const std::shared_ptr<Logger>& LogFactory::getInstance()
{ {
if(!logger_) { if(!logger_) {
std::shared_ptr<Logger> slogger(new Logger()); auto slogger = std::make_shared<Logger>();
openLogger(slogger); openLogger(slogger);
logger_.swap(slogger); logger_.swap(slogger);
} }

View File

@ -67,7 +67,8 @@ void Logger::openFile(const std::string& filename)
if(filename == DEV_STDOUT) { if(filename == DEV_STDOUT) {
fpp_ = global::cout(); fpp_ = global::cout();
} else { } else {
fpp_.reset(new BufferedFile(filename.c_str(), BufferedFile::APPEND)); fpp_ = std::make_shared<BufferedFile>(filename.c_str(),
BufferedFile::APPEND);
if(!*static_cast<BufferedFile*>(fpp_.get())) { if(!*static_cast<BufferedFile*>(fpp_.get())) {
throw DL_ABORT_EX(fmt(EX_FILE_OPEN, filename.c_str(), "n/a")); throw DL_ABORT_EX(fmt(EX_FILE_OPEN, filename.c_str(), "n/a"));
} }

View File

@ -65,7 +65,7 @@ bool LpdMessageDispatcher::init(const std::string& localAddr,
unsigned char ttl, unsigned char loop) unsigned char ttl, unsigned char loop)
{ {
try { try {
socket_.reset(new SocketCore(SOCK_DGRAM)); socket_ = std::make_shared<SocketCore>(SOCK_DGRAM);
socket_->create(AF_INET); socket_->create(AF_INET);
A2_LOG_DEBUG(fmt("Setting multicast outgoing interface=%s", A2_LOG_DEBUG(fmt("Setting multicast outgoing interface=%s",
localAddr.c_str())); localAddr.c_str()));

View File

@ -81,20 +81,15 @@ MSEHandshake::MSEHandshake
rbufLength_(0), rbufLength_(0),
socketBuffer_(socket), socketBuffer_(socket),
negotiatedCryptoType_(CRYPTO_NONE), negotiatedCryptoType_(CRYPTO_NONE),
dh_(nullptr),
initiator_(true), initiator_(true),
markerIndex_(0), markerIndex_(0),
padLength_(0), padLength_(0),
iaLength_(0), iaLength_(0),
ia_(nullptr),
sha1_(MessageDigest::sha1()) sha1_(MessageDigest::sha1())
{} {}
MSEHandshake::~MSEHandshake() MSEHandshake::~MSEHandshake()
{ {}
delete dh_;
delete [] ia_;
}
MSEHandshake::HANDSHAKE_TYPE MSEHandshake::identifyHandshakeType() MSEHandshake::HANDSHAKE_TYPE MSEHandshake::identifyHandshakeType()
{ {
@ -115,8 +110,7 @@ MSEHandshake::HANDSHAKE_TYPE MSEHandshake::identifyHandshakeType()
void MSEHandshake::initEncryptionFacility(bool initiator) void MSEHandshake::initEncryptionFacility(bool initiator)
{ {
delete dh_; dh_ = make_unique<DHKeyExchange>();
dh_ = new DHKeyExchange();
dh_->init(PRIME, PRIME_BITS, GENERATOR, 160); dh_->init(PRIME, PRIME_BITS, GENERATOR, 160);
dh_->generatePublicKey(); dh_->generatePublicKey();
A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - DH initialized.", cuid_)); A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - DH initialized.", cuid_));
@ -501,9 +495,8 @@ bool MSEHandshake::receiveReceiverIA()
wantRead_ = true; wantRead_ = true;
return false; return false;
} }
delete [] ia_; ia_ = make_unique<unsigned char[]>(iaLength_);
ia_ = new unsigned char[iaLength_]; decryptor_->encrypt(iaLength_, ia_.get(), rbuf_);
decryptor_->encrypt(iaLength_, ia_, rbuf_);
A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - IA received.", cuid_)); A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - IA received.", cuid_));
// shift rbuf_ // shift rbuf_
shiftBuffer(iaLength_); shiftBuffer(iaLength_);

View File

@ -87,7 +87,7 @@ private:
SocketBuffer socketBuffer_; SocketBuffer socketBuffer_;
CRYPTO_TYPE negotiatedCryptoType_; CRYPTO_TYPE negotiatedCryptoType_;
DHKeyExchange* dh_; std::unique_ptr<DHKeyExchange> dh_;
std::unique_ptr<ARC4Encryptor> encryptor_; std::unique_ptr<ARC4Encryptor> encryptor_;
std::unique_ptr<ARC4Encryptor> decryptor_; std::unique_ptr<ARC4Encryptor> decryptor_;
unsigned char infoHash_[INFO_HASH_LENGTH]; unsigned char infoHash_[INFO_HASH_LENGTH];
@ -97,7 +97,7 @@ private:
size_t markerIndex_; size_t markerIndex_;
uint16_t padLength_; uint16_t padLength_;
uint16_t iaLength_; uint16_t iaLength_;
unsigned char* ia_; std::unique_ptr<unsigned char[]> ia_;
std::unique_ptr<MessageDigest> sha1_; std::unique_ptr<MessageDigest> sha1_;
void encryptAndSendData(unsigned char* data, size_t length); void encryptAndSendData(unsigned char* data, size_t length);
@ -179,7 +179,7 @@ public:
// returns plain text IA // returns plain text IA
const unsigned char* getIA() const const unsigned char* getIA() const
{ {
return ia_; return ia_.get();
} }
size_t getIALength() const size_t getIALength() const

View File

@ -171,11 +171,11 @@ void Netrc::parse(const std::string& path)
if(state == GET_TOKEN) { if(state == GET_TOKEN) {
if(util::streq((*iter).first, (*iter).second, "machine")) { if(util::streq((*iter).first, (*iter).second, "machine")) {
storeAuthenticator(std::move(authenticator)); storeAuthenticator(std::move(authenticator));
authenticator.reset(new Authenticator()); authenticator = make_unique<Authenticator>();
state = SET_MACHINE; state = SET_MACHINE;
} else if(util::streq((*iter).first, (*iter).second, "default")) { } else if(util::streq((*iter).first, (*iter).second, "default")) {
storeAuthenticator(std::move(authenticator)); storeAuthenticator(std::move(authenticator));
authenticator.reset(new DefaultAuthenticator()); authenticator = make_unique<DefaultAuthenticator>();
} else { } else {
if(!authenticator) { if(!authenticator) {
throw DL_ABORT_EX throw DL_ABORT_EX

View File

@ -64,8 +64,7 @@ OptionHandlerException::~OptionHandlerException() throw() {}
std::shared_ptr<Exception> OptionHandlerException::copy() const std::shared_ptr<Exception> OptionHandlerException::copy() const
{ {
std::shared_ptr<Exception> e(new OptionHandlerException(*this)); return std::make_shared<OptionHandlerException>(*this);
return e;
} }
} // namespace aria2 } // namespace aria2

View File

@ -352,7 +352,7 @@ std::shared_ptr<OptionParser> OptionParser::optionParser_;
const std::shared_ptr<OptionParser>& OptionParser::getInstance() const std::shared_ptr<OptionParser>& OptionParser::getInstance()
{ {
if(!optionParser_) { if(!optionParser_) {
optionParser_.reset(new OptionParser()); optionParser_ = std::make_shared<OptionParser>();
optionParser_->setOptionHandlers(OptionHandlerFactory::createOptionHandlers()); optionParser_->setOptionHandlers(OptionHandlerFactory::createOptionHandlers());
} }
return optionParser_; return optionParser_;

View File

@ -195,7 +195,7 @@ void PeerAbstractCommand::updateKeepAlive()
void PeerAbstractCommand::createSocket() void PeerAbstractCommand::createSocket()
{ {
socket_.reset(new SocketCore()); socket_ = std::make_shared<SocketCore>();
} }
void PeerAbstractCommand::addCommandSelf() void PeerAbstractCommand::addCommandSelf()

View File

@ -70,7 +70,7 @@ PeerConnection::PeerConnection
socket_(socket), socket_(socket),
msgState_(BT_MSG_PREV_READ_LENGTH), msgState_(BT_MSG_PREV_READ_LENGTH),
bufferCapacity_(MAX_BUFFER_CAPACITY), bufferCapacity_(MAX_BUFFER_CAPACITY),
resbuf_(new unsigned char[bufferCapacity_]), resbuf_(make_unique<unsigned char[]>(bufferCapacity_)),
resbufLength_(0), resbufLength_(0),
currentPayloadLength_(0), currentPayloadLength_(0),
resbufOffset_(0), resbufOffset_(0),
@ -81,9 +81,7 @@ PeerConnection::PeerConnection
{} {}
PeerConnection::~PeerConnection() PeerConnection::~PeerConnection()
{ {}
delete [] resbuf_;
}
void PeerConnection::pushBytes(unsigned char* data, size_t len, void PeerConnection::pushBytes(unsigned char* data, size_t len,
std::unique_ptr<ProgressUpdate> progressUpdate) std::unique_ptr<ProgressUpdate> progressUpdate)
@ -142,7 +140,7 @@ bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength)
resbufOffset_ = i; resbufOffset_ = i;
if(done) { if(done) {
if(data) { if(data) {
memcpy(data, resbuf_ + msgOffset_ + 4, currentPayloadLength_); memcpy(data, resbuf_.get() + msgOffset_ + 4, currentPayloadLength_);
} }
dataLength = currentPayloadLength_; dataLength = currentPayloadLength_;
return true; return true;
@ -158,7 +156,8 @@ bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength)
} else { } else {
// Shift buffer so that resbuf_[msgOffset_] moves to // Shift buffer so that resbuf_[msgOffset_] moves to
// rebuf_[0]. // rebuf_[0].
memmove(resbuf_, resbuf_ + msgOffset_, resbufLength_ - msgOffset_); memmove(resbuf_.get(), resbuf_.get() + msgOffset_,
resbufLength_ - msgOffset_);
resbufLength_ -= msgOffset_; resbufLength_ -= msgOffset_;
resbufOffset_ = resbufLength_; resbufOffset_ = resbufLength_;
msgOffset_ = 0; msgOffset_ = 0;
@ -172,7 +171,7 @@ bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength)
} else { } else {
nread = bufferCapacity_ - resbufLength_; nread = bufferCapacity_ - resbufLength_;
} }
readData(resbuf_+resbufLength_, nread, encryptionEnabled_); readData(resbuf_.get() +resbufLength_, nread, encryptionEnabled_);
if(nread == 0) { if(nread == 0) {
if(socket_->wantRead() || socket_->wantWrite()) { if(socket_->wantRead() || socket_->wantWrite()) {
break; break;
@ -198,7 +197,7 @@ bool PeerConnection::receiveHandshake(unsigned char* data, size_t& dataLength,
size_t remaining = BtHandshakeMessage::MESSAGE_LENGTH-resbufLength_; size_t remaining = BtHandshakeMessage::MESSAGE_LENGTH-resbufLength_;
if(remaining > 0) { if(remaining > 0) {
size_t temp = remaining; size_t temp = remaining;
readData(resbuf_+resbufLength_, remaining, encryptionEnabled_); readData(resbuf_.get()+resbufLength_, remaining, encryptionEnabled_);
if(remaining == 0 && !socket_->wantRead() && !socket_->wantWrite()) { if(remaining == 0 && !socket_->wantRead() && !socket_->wantWrite()) {
// we got EOF // we got EOF
A2_LOG_DEBUG A2_LOG_DEBUG
@ -214,7 +213,7 @@ bool PeerConnection::receiveHandshake(unsigned char* data, size_t& dataLength,
} }
} }
size_t writeLength = std::min(resbufLength_, dataLength); size_t writeLength = std::min(resbufLength_, dataLength);
memcpy(data, resbuf_, writeLength); memcpy(data, resbuf_.get(), writeLength);
dataLength = writeLength; dataLength = writeLength;
if(retval && !peek) { if(retval && !peek) {
resbufLength_ = 0; resbufLength_ = 0;
@ -244,7 +243,7 @@ void PeerConnection::enableEncryption
void PeerConnection::presetBuffer(const unsigned char* data, size_t length) void PeerConnection::presetBuffer(const unsigned char* data, size_t length)
{ {
size_t nwrite = std::min(bufferCapacity_, length); size_t nwrite = std::min(bufferCapacity_, length);
memcpy(resbuf_, data, nwrite); memcpy(resbuf_.get(), data, nwrite);
resbufLength_ = length; resbufLength_ = length;
} }
@ -267,17 +266,16 @@ ssize_t PeerConnection::sendPendingData()
const unsigned char* PeerConnection::getMsgPayloadBuffer() const const unsigned char* PeerConnection::getMsgPayloadBuffer() const
{ {
return resbuf_ + msgOffset_ + 4; return resbuf_.get() + msgOffset_ + 4;
} }
void PeerConnection::reserveBuffer(size_t minSize) void PeerConnection::reserveBuffer(size_t minSize)
{ {
if(bufferCapacity_ < minSize) { if(bufferCapacity_ < minSize) {
bufferCapacity_ = minSize; bufferCapacity_ = minSize;
auto buf = new unsigned char[bufferCapacity_]; auto buf = make_unique<unsigned char[]>(bufferCapacity_);
memcpy(buf, resbuf_, resbufLength_); memcpy(buf.get(), resbuf_.get(), resbufLength_);
delete [] resbuf_; resbuf_ = std::move(buf);
resbuf_ = buf;
} }
} }

View File

@ -64,7 +64,7 @@ private:
// The capacity of the buffer resbuf_ // The capacity of the buffer resbuf_
size_t bufferCapacity_; size_t bufferCapacity_;
// The internal buffer of incoming handshakes and messages // The internal buffer of incoming handshakes and messages
unsigned char* resbuf_; std::unique_ptr<unsigned char[]> resbuf_;
// The number of bytes written in resbuf_ // The number of bytes written in resbuf_
size_t resbufLength_; size_t resbufLength_;
// The length of message (not handshake) currently receiving // The length of message (not handshake) currently receiving
@ -124,7 +124,7 @@ public:
const unsigned char* getBuffer() const const unsigned char* getBuffer() const
{ {
return resbuf_; return resbuf_.get();
} }
size_t getBufferLength() const size_t getBufferLength() const

View File

@ -65,7 +65,7 @@ PeerListenCommand::~PeerListenCommand() {}
bool PeerListenCommand::bindPort(uint16_t& port, SegList<int>& sgl) bool PeerListenCommand::bindPort(uint16_t& port, SegList<int>& sgl)
{ {
socket_.reset(new SocketCore()); socket_ = std::make_shared<SocketCore>();
std::vector<uint16_t> ports; std::vector<uint16_t> ports;
while(sgl.hasNext()) { while(sgl.hasNext()) {
ports.push_back(sgl.next()); ports.push_back(sgl.next());
@ -114,7 +114,8 @@ bool PeerListenCommand::execute() {
std::pair<std::string, uint16_t> peerInfo; std::pair<std::string, uint16_t> peerInfo;
peerSocket->getPeerInfo(peerInfo); peerSocket->getPeerInfo(peerInfo);
std::shared_ptr<Peer> peer(new Peer(peerInfo.first, peerInfo.second, true)); auto peer = std::make_shared<Peer>(peerInfo.first, peerInfo.second,
true);
cuid_t cuid = e_->newCUID(); cuid_t cuid = e_->newCUID();
e_->addCommand(make_unique<ReceiverMSEHandshakeCommand> e_->addCommand(make_unique<ReceiverMSEHandshakeCommand>
(cuid, peer, e_, peerSocket)); (cuid, peer, e_, peerSocket));

View File

@ -41,12 +41,13 @@
#include "A2STR.h" #include "A2STR.h"
#include "BtMessageDispatcher.h" #include "BtMessageDispatcher.h"
#include "wallclock.h" #include "wallclock.h"
#include "a2functional.h"
namespace aria2 { namespace aria2 {
PeerSessionResource::PeerSessionResource(int32_t pieceLength, int64_t totalLength) PeerSessionResource::PeerSessionResource(int32_t pieceLength, int64_t totalLength)
: :
bitfieldMan_(new BitfieldMan(pieceLength, totalLength)), bitfieldMan_(make_unique<BitfieldMan>(pieceLength, totalLength)),
lastDownloadUpdate_(0), lastDownloadUpdate_(0),
lastAmUnchoking_(0), lastAmUnchoking_(0),
dispatcher_(nullptr), dispatcher_(nullptr),
@ -63,9 +64,7 @@ PeerSessionResource::PeerSessionResource(int32_t pieceLength, int64_t totalLengt
{} {}
PeerSessionResource::~PeerSessionResource() PeerSessionResource::~PeerSessionResource()
{ {}
delete bitfieldMan_;
}
void PeerSessionResource::amChoking(bool b) void PeerSessionResource::amChoking(bool b)
{ {
@ -251,8 +250,7 @@ size_t PeerSessionResource::countOutstandingUpload() const
void PeerSessionResource::reconfigure(int32_t pieceLength, int64_t totalLenth) void PeerSessionResource::reconfigure(int32_t pieceLength, int64_t totalLenth)
{ {
delete bitfieldMan_; bitfieldMan_ = make_unique<BitfieldMan>(pieceLength, totalLenth);
bitfieldMan_ = new BitfieldMan(pieceLength, totalLenth);
} }
} // namespace aria2 } // namespace aria2

View File

@ -39,6 +39,7 @@
#include <string> #include <string>
#include <set> #include <set>
#include <memory>
#include "BtConstants.h" #include "BtConstants.h"
#include "NetStat.h" #include "NetStat.h"
@ -52,7 +53,7 @@ class BtMessageDispatcher;
class PeerSessionResource { class PeerSessionResource {
private: private:
BitfieldMan* bitfieldMan_; std::unique_ptr<BitfieldMan> bitfieldMan_;
// fast index set which a peer has sent to localhost. // fast index set which a peer has sent to localhost.
std::set<size_t> peerAllowedIndexSet_; std::set<size_t> peerAllowedIndexSet_;
// fast index set which localhost has sent to a peer. // fast index set which localhost has sent to a peer.

View File

@ -51,17 +51,14 @@
namespace aria2 { namespace aria2 {
Piece::Piece() Piece::Piece()
: bitfield_(nullptr), : index_(0),
wrCache_(nullptr),
index_(0),
length_(0), length_(0),
nextBegin_(0), nextBegin_(0),
usedBySegment_(false) usedBySegment_(false)
{} {}
Piece::Piece(size_t index, int64_t length, int32_t blockLength) Piece::Piece(size_t index, int64_t length, int32_t blockLength)
: bitfield_(new BitfieldMan(blockLength, length)), : bitfield_(make_unique<BitfieldMan>(blockLength, length)),
wrCache_(nullptr),
index_(index), index_(index),
length_(length), length_(length),
nextBegin_(0), nextBegin_(0),
@ -69,10 +66,7 @@ Piece::Piece(size_t index, int64_t length, int32_t blockLength)
{} {}
Piece::~Piece() Piece::~Piece()
{ {}
delete wrCache_;
delete bitfield_;
}
void Piece::completeBlock(size_t blockIndex) { void Piece::completeBlock(size_t blockIndex) {
bitfield_->setBit(blockIndex); bitfield_->setBit(blockIndex);
@ -185,7 +179,6 @@ std::string Piece::toString() const {
void Piece::reconfigure(int64_t length) void Piece::reconfigure(int64_t length)
{ {
delete bitfield_;
length_ = length; length_ = length;
// TODO currently, this function is only called from // TODO currently, this function is only called from
// GrowSegment::updateWrittenLength(). If we use default block // GrowSegment::updateWrittenLength(). If we use default block
@ -193,7 +186,8 @@ void Piece::reconfigure(int64_t length)
// BitfieldMan for each call is very expensive. Therefore, we use // BitfieldMan for each call is very expensive. Therefore, we use
// maximum block length for now to reduce the overhead. Ideally, we // maximum block length for now to reduce the overhead. Ideally, we
// check the code thoroughly and remove bitfield_ if we can. // check the code thoroughly and remove bitfield_ if we can.
bitfield_ = new BitfieldMan(std::numeric_limits<int32_t>::max(), length_); bitfield_ = make_unique<BitfieldMan>(std::numeric_limits<int32_t>::max(),
length_);
} }
void Piece::setBitfield(const unsigned char* bitfield, size_t len) void Piece::setBitfield(const unsigned char* bitfield, size_t len)
@ -323,9 +317,9 @@ void Piece::initWrCache(WrDiskCache* diskCache,
if(!diskCache) { if(!diskCache) {
return; return;
} }
assert(wrCache_ == nullptr); assert(!wrCache_);
wrCache_ = new WrDiskCacheEntry(diskAdaptor); wrCache_ = make_unique<WrDiskCacheEntry>(diskAdaptor);
bool rv = diskCache->add(wrCache_); bool rv = diskCache->add(wrCache_.get());
assert(rv); assert(rv);
} }
@ -336,7 +330,7 @@ void Piece::flushWrCache(WrDiskCache* diskCache)
} }
assert(wrCache_); assert(wrCache_);
ssize_t size = static_cast<ssize_t>(wrCache_->getSize()); ssize_t size = static_cast<ssize_t>(wrCache_->getSize());
diskCache->update(wrCache_, -size); diskCache->update(wrCache_.get(), -size);
wrCache_->writeToDisk(); wrCache_->writeToDisk();
} }
@ -347,7 +341,7 @@ void Piece::clearWrCache(WrDiskCache* diskCache)
} }
assert(wrCache_); assert(wrCache_);
ssize_t size = static_cast<ssize_t>(wrCache_->getSize()); ssize_t size = static_cast<ssize_t>(wrCache_->getSize());
diskCache->update(wrCache_, -size); diskCache->update(wrCache_.get(), -size);
wrCache_->clear(); wrCache_->clear();
} }
@ -359,7 +353,7 @@ void Piece::updateWrCache(WrDiskCache* diskCache, unsigned char* data,
return; return;
} }
assert(wrCache_); assert(wrCache_);
A2_LOG_DEBUG(fmt("updateWrCache entry=%p", wrCache_)); A2_LOG_DEBUG(fmt("updateWrCache entry=%p", wrCache_.get()));
auto cell = new WrDiskCacheEntry::DataCell(); auto cell = new WrDiskCacheEntry::DataCell();
cell->goff = goff; cell->goff = goff;
cell->data = data; cell->data = data;
@ -369,7 +363,7 @@ void Piece::updateWrCache(WrDiskCache* diskCache, unsigned char* data,
bool rv; bool rv;
rv = wrCache_->cacheData(cell); rv = wrCache_->cacheData(cell);
assert(rv); assert(rv);
rv = diskCache->update(wrCache_, len); rv = diskCache->update(wrCache_.get(), len);
assert(rv); assert(rv);
} }
@ -383,7 +377,7 @@ size_t Piece::appendWrCache(WrDiskCache* diskCache, int64_t goff,
size_t delta = wrCache_->append(goff, data, len); size_t delta = wrCache_->append(goff, data, len);
bool rv; bool rv;
if(delta > 0) { if(delta > 0) {
rv = diskCache->update(wrCache_, delta); rv = diskCache->update(wrCache_.get(), delta);
assert(rv); assert(rv);
} }
return delta; return delta;
@ -392,9 +386,8 @@ size_t Piece::appendWrCache(WrDiskCache* diskCache, int64_t goff,
void Piece::releaseWrCache(WrDiskCache* diskCache) void Piece::releaseWrCache(WrDiskCache* diskCache)
{ {
if(diskCache && wrCache_) { if(diskCache && wrCache_) {
diskCache->remove(wrCache_); diskCache->remove(wrCache_.get());
delete wrCache_; wrCache_.reset();
wrCache_ = nullptr;
} }
} }

View File

@ -54,8 +54,8 @@ class MessageDigest;
class Piece { class Piece {
private: private:
BitfieldMan* bitfield_; std::unique_ptr<BitfieldMan> bitfield_;
WrDiskCacheEntry* wrCache_; std::unique_ptr<WrDiskCacheEntry> wrCache_;
std::unique_ptr<MessageDigest> mdctx_; std::unique_ptr<MessageDigest> mdctx_;
std::vector<cuid_t> users_; std::vector<cuid_t> users_;
std::string hashType_; std::string hashType_;
@ -204,7 +204,7 @@ public:
void releaseWrCache(WrDiskCache* diskCache); void releaseWrCache(WrDiskCache* diskCache);
WrDiskCacheEntry* getWrDiskCacheEntry() const WrDiskCacheEntry* getWrDiskCacheEntry() const
{ {
return wrCache_; return wrCache_.get();
} }
}; };

View File

@ -61,16 +61,14 @@ ReceiverMSEHandshakeCommand::ReceiverMSEHandshakeCommand
PeerAbstractCommand(cuid, peer, e, s), PeerAbstractCommand(cuid, peer, e, s),
sequence_(RECEIVER_IDENTIFY_HANDSHAKE), sequence_(RECEIVER_IDENTIFY_HANDSHAKE),
mseHandshake_(new MSEHandshake(cuid, s, e->getOption())) mseHandshake_(make_unique<MSEHandshake>(cuid, s, e->getOption()))
{ {
setTimeout(e->getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT)); setTimeout(e->getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT));
mseHandshake_->setWantRead(true); mseHandshake_->setWantRead(true);
} }
ReceiverMSEHandshakeCommand::~ReceiverMSEHandshakeCommand() ReceiverMSEHandshakeCommand::~ReceiverMSEHandshakeCommand()
{ {}
delete mseHandshake_;
}
bool ReceiverMSEHandshakeCommand::exitBeforeExecute() bool ReceiverMSEHandshakeCommand::exitBeforeExecute()
{ {

View File

@ -60,7 +60,7 @@ public:
private: private:
Seq sequence_; Seq sequence_;
MSEHandshake* mseHandshake_; std::unique_ptr<MSEHandshake> mseHandshake_;
void createCommand(); void createCommand();
protected: protected:

View File

@ -38,8 +38,7 @@ namespace aria2 {
std::shared_ptr<Exception> RecoverableException::copy() const std::shared_ptr<Exception> RecoverableException::copy() const
{ {
std::shared_ptr<Exception> e(new RecoverableException(*this)); return std::make_shared<RecoverableException>(*this);
return e;
} }
RecoverableException::RecoverableException RecoverableException::RecoverableException

View File

@ -168,7 +168,7 @@ const std::shared_ptr<PeerStat>& Request::initPeerStat()
assert(v == 0); assert(v == 0);
std::string host = uri::getFieldString(us, USR_HOST, uri_.c_str()); std::string host = uri::getFieldString(us, USR_HOST, uri_.c_str());
std::string protocol = uri::getFieldString(us, USR_SCHEME, uri_.c_str()); std::string protocol = uri::getFieldString(us, USR_SCHEME, uri_.c_str());
peerStat_.reset(new PeerStat(0, host, protocol)); peerStat_ = std::make_shared<PeerStat>(0, host, protocol);
return peerStat_; return peerStat_;
} }

View File

@ -124,7 +124,7 @@ RequestGroup::RequestGroup(const std::shared_ptr<GroupId>& gid,
: belongsToGID_(0), : belongsToGID_(0),
gid_(gid), gid_(gid),
option_(option), option_(option),
progressInfoFile_(new NullProgressInfoFile()), progressInfoFile_(std::make_shared<NullProgressInfoFile>()),
uriSelector_(make_unique<InorderURISelector>()), uriSelector_(make_unique<InorderURISelector>()),
requestGroupMan_(nullptr), requestGroupMan_(nullptr),
#ifdef ENABLE_BITTORRENT #ifdef ENABLE_BITTORRENT
@ -1123,7 +1123,7 @@ std::shared_ptr<DownloadResult> RequestGroup::createDownloadResult() const
A2_LOG_DEBUG(fmt("GID#%s - Creating DownloadResult.", A2_LOG_DEBUG(fmt("GID#%s - Creating DownloadResult.",
gid_->toHex().c_str())); gid_->toHex().c_str()));
TransferStat st = calculateStat(); TransferStat st = calculateStat();
std::shared_ptr<DownloadResult> res(new DownloadResult()); auto res = std::make_shared<DownloadResult>();
res->gid = gid_; res->gid = gid_;
res->fileEntries = downloadContext_->getFileEntries(); res->fileEntries = downloadContext_->getFileEntries();
res->inMemoryDownload = inMemoryDownload_; res->inMemoryDownload = inMemoryDownload_;

View File

@ -106,7 +106,7 @@ RequestGroupMan::RequestGroupMan
const Option* option) const Option* option)
: maxSimultaneousDownloads_(maxSimultaneousDownloads), : maxSimultaneousDownloads_(maxSimultaneousDownloads),
option_(option), option_(option),
serverStatMan_(new ServerStatMan()), serverStatMan_(std::make_shared<ServerStatMan>()),
maxOverallDownloadSpeedLimit_ maxOverallDownloadSpeedLimit_
(option->getAsInt(PREF_MAX_OVERALL_DOWNLOAD_LIMIT)), (option->getAsInt(PREF_MAX_OVERALL_DOWNLOAD_LIMIT)),
maxOverallUploadSpeedLimit_(option->getAsInt maxOverallUploadSpeedLimit_(option->getAsInt
@ -116,7 +116,6 @@ RequestGroupMan::RequestGroupMan
removedErrorResult_(0), removedErrorResult_(0),
removedLastErrorResult_(error_code::FINISHED), removedLastErrorResult_(error_code::FINISHED),
maxDownloadResult_(option->getAsInt(PREF_MAX_DOWNLOAD_RESULT)), maxDownloadResult_(option->getAsInt(PREF_MAX_DOWNLOAD_RESULT)),
wrDiskCache_(nullptr),
openedFileCounter_(std::make_shared<OpenedFileCounter> openedFileCounter_(std::make_shared<OpenedFileCounter>
(this, option->getAsInt(PREF_BT_MAX_OPEN_FILES))), (this, option->getAsInt(PREF_BT_MAX_OPEN_FILES))),
numStoppedTotal_(0) numStoppedTotal_(0)
@ -128,7 +127,6 @@ RequestGroupMan::RequestGroupMan
RequestGroupMan::~RequestGroupMan() RequestGroupMan::~RequestGroupMan()
{ {
openedFileCounter_->deactivate(); openedFileCounter_->deactivate();
delete wrDiskCache_;
} }
bool RequestGroupMan::downloadFinished() bool RequestGroupMan::downloadFinished()
@ -871,7 +869,7 @@ RequestGroupMan::getOrCreateServerStat(const std::string& hostname,
{ {
std::shared_ptr<ServerStat> ss = findServerStat(hostname, protocol); std::shared_ptr<ServerStat> ss = findServerStat(hostname, protocol);
if(!ss) { if(!ss) {
ss.reset(new ServerStat(hostname, protocol)); ss = std::make_shared<ServerStat>(hostname, protocol);
addServerStat(ss); addServerStat(ss);
} }
return ss; return ss;
@ -960,10 +958,10 @@ void RequestGroupMan::setUriListParser
void RequestGroupMan::initWrDiskCache() void RequestGroupMan::initWrDiskCache()
{ {
assert(wrDiskCache_ == nullptr); assert(!wrDiskCache_);
size_t limit = option_->getAsInt(PREF_DISK_CACHE); size_t limit = option_->getAsInt(PREF_DISK_CACHE);
if(limit > 0) { if(limit > 0) {
wrDiskCache_ = new WrDiskCache(limit); wrDiskCache_ = make_unique<WrDiskCache>(limit);
} }
} }

View File

@ -103,7 +103,7 @@ private:
// UriListParser for deferred input. // UriListParser for deferred input.
std::shared_ptr<UriListParser> uriListParser_; std::shared_ptr<UriListParser> uriListParser_;
WrDiskCache* wrDiskCache_; std::unique_ptr<WrDiskCache> wrDiskCache_;
std::shared_ptr<OpenedFileCounter> openedFileCounter_; std::shared_ptr<OpenedFileCounter> openedFileCounter_;
@ -340,7 +340,7 @@ public:
WrDiskCache* getWrDiskCache() const WrDiskCache* getWrDiskCache() const
{ {
return wrDiskCache_; return wrDiskCache_.get();
} }
// Initializes WrDiskCache according to PREF_DISK_CACHE option. If // Initializes WrDiskCache according to PREF_DISK_CACHE option. If

View File

@ -150,11 +150,12 @@ std::shared_ptr<Segment> SegmentMan::checkoutSegment
piece->setUsedBySegment(true); piece->setUsedBySegment(true);
std::shared_ptr<Segment> segment; std::shared_ptr<Segment> segment;
if(piece->getLength() == 0) { if(piece->getLength() == 0) {
segment.reset(new GrowSegment(piece)); segment = std::make_shared<GrowSegment>(piece);
} else { } else {
segment.reset(new PiecedSegment(downloadContext_->getPieceLength(), piece)); segment = std::make_shared<PiecedSegment>
(downloadContext_->getPieceLength(), piece);
} }
std::shared_ptr<SegmentEntry> entry(new SegmentEntry(cuid, segment)); auto entry = std::make_shared<SegmentEntry>(cuid, segment);
usedSegmentEntries_.push_back(entry); usedSegmentEntries_.push_back(entry);
A2_LOG_DEBUG(fmt("index=%lu, length=%" PRId64 ", segmentLength=%" PRId64 "," A2_LOG_DEBUG(fmt("index=%lu, length=%" PRId64 ", segmentLength=%" PRId64 ","
" writtenLength=%" PRId64, " writtenLength=%" PRId64,

View File

@ -59,7 +59,7 @@ ServerStatMan::~ServerStatMan() {}
std::shared_ptr<ServerStat> ServerStatMan::find(const std::string& hostname, std::shared_ptr<ServerStat> ServerStatMan::find(const std::string& hostname,
const std::string& protocol) const const std::string& protocol) const
{ {
std::shared_ptr<ServerStat> ss(new ServerStat(hostname, protocol)); auto ss = std::make_shared<ServerStat>(hostname, protocol);
auto i = serverStats_.find(ss); auto i = serverStats_.find(ss);
if(i == serverStats_.end()) { if(i == serverStats_.end()) {
return nullptr; return nullptr;
@ -193,7 +193,7 @@ bool ServerStatMan::load(const std::string& filename)
if(m[S_HOST].empty() || m[S_PROTOCOL].empty()) { if(m[S_HOST].empty() || m[S_PROTOCOL].empty()) {
continue; continue;
} }
std::shared_ptr<ServerStat> sstat(new ServerStat(m[S_HOST], m[S_PROTOCOL])); auto sstat = std::make_shared<ServerStat>(m[S_HOST], m[S_PROTOCOL]);
uint32_t uintval; uint32_t uintval;
if(!util::parseUIntNoThrow(uintval, m[S_DL_SPEED])) { if(!util::parseUIntNoThrow(uintval, m[S_DL_SPEED])) {

View File

@ -77,12 +77,12 @@ bool SessionSerializer::save(const std::string& filename) const
std::shared_ptr<IOFile> fp; std::shared_ptr<IOFile> fp;
#if HAVE_ZLIB #if HAVE_ZLIB
if (util::endsWith(filename, ".gz")) { if (util::endsWith(filename, ".gz")) {
fp.reset(new GZipFile(tempFilename.c_str(), IOFile::WRITE)); fp = std::make_shared<GZipFile>(tempFilename.c_str(), IOFile::WRITE);
} }
else else
#endif #endif
{ {
fp.reset(new BufferedFile(tempFilename.c_str(), IOFile::WRITE)); fp = std::make_shared<BufferedFile>(tempFilename.c_str(), IOFile::WRITE);
} }
if(!*fp) { if(!*fp) {
return false; return false;

View File

@ -41,6 +41,7 @@
#include <cstring> #include <cstring>
#include "a2time.h" #include "a2time.h"
#include "a2functional.h"
namespace aria2 { namespace aria2 {

View File

@ -355,7 +355,7 @@ std::shared_ptr<SocketCore> SocketCore::acceptConnection() const
if(fd == (sock_t) -1) { if(fd == (sock_t) -1) {
throw DL_ABORT_EX(fmt(EX_SOCKET_ACCEPT, errorMsg(errNum).c_str())); throw DL_ABORT_EX(fmt(EX_SOCKET_ACCEPT, errorMsg(errNum).c_str()));
} }
std::shared_ptr<SocketCore> sock(new SocketCore(fd, sockType_)); auto sock = std::shared_ptr<SocketCore>(new SocketCore(fd, sockType_));
sock->setNonBlockingMode(); sock->setNonBlockingMode();
return sock; return sock;
} }

View File

@ -179,7 +179,7 @@ int UDPTrackerClient::receiveReply
} }
req->state = UDPT_STA_COMPLETE; req->state = UDPT_STA_COMPLETE;
req->reply.reset(new UDPTrackerReply()); req->reply = std::make_shared<UDPTrackerReply>();
req->reply->action = action; req->reply->action = action;
req->reply->transactionId = transactionId; req->reply->transactionId = transactionId;
req->reply->interval = bittorrent::getIntParam(data, 8); req->reply->interval = bittorrent::getIntParam(data, 8);
@ -265,7 +265,7 @@ ssize_t UDPTrackerClient::createRequest
req->remotePort, req->remotePort,
now); now);
if(!c) { if(!c) {
std::shared_ptr<UDPTrackerRequest> creq(new UDPTrackerRequest()); auto creq = std::make_shared<UDPTrackerRequest>();
creq->action = UDPT_ACT_CONNECT; creq->action = UDPT_ACT_CONNECT;
creq->remoteAddr = req->remoteAddr; creq->remoteAddr = req->remoteAddr;
creq->remotePort = req->remotePort; creq->remotePort = req->remotePort;

View File

@ -61,8 +61,7 @@ UnknownOptionException::~UnknownOptionException() throw() {}
std::shared_ptr<Exception> UnknownOptionException::copy() const std::shared_ptr<Exception> UnknownOptionException::copy() const
{ {
std::shared_ptr<Exception> e(new UnknownOptionException(*this)); return std::make_shared<UnknownOptionException>(*this);
return e;
} }
} // namespace aria2 } // namespace aria2

View File

@ -53,9 +53,9 @@ namespace aria2 {
UriListParser::UriListParser(const std::string& filename) UriListParser::UriListParser(const std::string& filename)
#if HAVE_ZLIB #if HAVE_ZLIB
: fp_(new GZipFile(filename.c_str(), IOFile::READ)) : fp_(make_unique<GZipFile>(filename.c_str(), IOFile::READ))
#else #else
: fp_(new BufferedFile(filename.c_str(), IOFile::READ)) : fp_(make_unique<BufferedFile>(filename.c_str(), IOFile::READ))
#endif #endif
{} {}

View File

@ -49,7 +49,7 @@ namespace aria2 {
class UriListParser { class UriListParser {
private: private:
std::shared_ptr<IOFile> fp_; std::unique_ptr<IOFile> fp_;
std::string line_; std::string line_;
public: public:

View File

@ -69,7 +69,7 @@
namespace aria2 { namespace aria2 {
Session::Session(const KeyVals& options) Session::Session(const KeyVals& options)
: context(new Context(false, 0, nullptr, options)) : context(std::make_shared<Context>(false, 0, nullptr, options))
{} {}
Session::~Session() Session::~Session()
@ -270,7 +270,7 @@ int addUri(Session* session,
int position) int position)
{ {
auto& e = session->context->reqinfo->getDownloadEngine(); auto& e = session->context->reqinfo->getDownloadEngine();
std::shared_ptr<Option> requestOption(new Option(*e->getOption())); auto requestOption = std::make_shared<Option>(*e->getOption());
try { try {
apiGatherRequestOption(requestOption.get(), options, apiGatherRequestOption(requestOption.get(), options,
OptionParser::getInstance()); OptionParser::getInstance());
@ -299,7 +299,7 @@ int addMetalink(Session* session,
{ {
#ifdef ENABLE_METALINK #ifdef ENABLE_METALINK
auto& e = session->context->reqinfo->getDownloadEngine(); auto& e = session->context->reqinfo->getDownloadEngine();
std::shared_ptr<Option> requestOption(new Option(*e->getOption())); auto requestOption = std::make_shared<Option>(*e->getOption());
std::vector<std::shared_ptr<RequestGroup> > result; std::vector<std::shared_ptr<RequestGroup> > result;
try { try {
apiGatherRequestOption(requestOption.get(), options, apiGatherRequestOption(requestOption.get(), options,
@ -338,7 +338,7 @@ int addTorrent(Session* session,
{ {
#ifdef ENABLE_BITTORRENT #ifdef ENABLE_BITTORRENT
auto& e = session->context->reqinfo->getDownloadEngine(); auto& e = session->context->reqinfo->getDownloadEngine();
std::shared_ptr<Option> requestOption(new Option(*e->getOption())); auto requestOption = std::make_shared<Option>(*e->getOption());
std::vector<std::shared_ptr<RequestGroup> > result; std::vector<std::shared_ptr<RequestGroup> > result;
try { try {
apiGatherRequestOption(requestOption.get(), options, apiGatherRequestOption(requestOption.get(), options,

View File

@ -52,15 +52,14 @@ Console consoleCerr;
void initConsole(bool suppress) void initConsole(bool suppress)
{ {
if(suppress) { if(suppress) {
consoleCerr.reset(new NullOutputFile()); consoleCout = consoleCerr = std::make_shared<NullOutputFile>();
consoleCout.reset(new NullOutputFile());
} else { } else {
#ifdef __MINGW32__ #ifdef __MINGW32__
consoleCout.reset(new WinConsoleFile(STD_OUTPUT_HANDLE)); consoleCout = std::make_shared<WinConsoleFile>(STD_OUTPUT_HANDLE);
consoleCerr.reset(new WinConsoleFile(STD_ERROR_HANDLE)); consoleCerr = std::make_shared<WinConsoleFile>(STD_ERROR_HANDLE);
#else // !__MINGW32__ #else // !__MINGW32__
consoleCout.reset(new BufferedFile(stdout)); consoleCout = std::make_shared<BufferedFile>(stdout);
consoleCerr.reset(new BufferedFile(stderr)); consoleCerr = std::make_shared<BufferedFile>(stderr);
#endif // !__MINGW32__ #endif // !__MINGW32__
} }
} }

View File

@ -221,7 +221,7 @@ error_code::Value option_processing(Option& op, bool standalone,
} }
} }
} }
std::shared_ptr<Option> confOption(new Option()); auto confOption = std::make_shared<Option>();
oparser->parseDefaultValues(*confOption); oparser->parseDefaultValues(*confOption);
if(!noConf) { if(!noConf) {
std::string cfname = std::string cfname =