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

pull/287/head
Tatsuhiro Tsujikawa 2014-09-13 00:07:21 +09:00
parent bee7a8317c
commit 2807258279
44 changed files with 136 additions and 161 deletions

View File

@ -748,7 +748,7 @@ std::shared_ptr<Request> AbstractCommand::createProxyRequest() const
std::string proxy = getProxyUri(req_->getProtocol(), getOption().get()); std::string proxy = getProxyUri(req_->getProtocol(), getOption().get());
if (!proxy.empty()) { if (!proxy.empty()) {
proxyRequest.reset(new Request()); proxyRequest = std::make_shared<Request>();
if (proxyRequest->setUri(proxy)) { if (proxyRequest->setUri(proxy)) {
A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Using proxy", getCuid())); A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Using proxy", getCuid()));
} }
@ -896,7 +896,7 @@ const std::shared_ptr<Option>& AbstractCommand::getOption() const
void AbstractCommand::createSocket() void AbstractCommand::createSocket()
{ {
socket_.reset(new SocketCore()); socket_ = std::make_shared<SocketCore>();
} }
int32_t AbstractCommand::calculateMinSplitSize() const int32_t AbstractCommand::calculateMinSplitSize() const

View File

@ -61,8 +61,8 @@ AbstractProxyRequestCommand::AbstractProxyRequestCommand
AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), AbstractCommand(cuid, req, fileEntry, requestGroup, e, s),
proxyRequest_(proxyRequest), proxyRequest_(proxyRequest),
httpConnection_ httpConnection_
(new HttpConnection (std::make_shared<HttpConnection>
(cuid, s, std::shared_ptr<SocketRecvBuffer>(new SocketRecvBuffer(s)))) (cuid, s, std::make_shared<SocketRecvBuffer>(s)))
{ {
setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT)); setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT));
disableReadCheckSocket(); disableReadCheckSocket();

View File

@ -116,7 +116,7 @@ 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

@ -150,23 +150,18 @@ ares_addr_node* parseAsyncDNSServers(const std::string& serversOpt)
ares_addr_node root; ares_addr_node root;
root.next = nullptr; root.next = nullptr;
ares_addr_node* tail = &root; ares_addr_node* tail = &root;
ares_addr_node* node = nullptr;
for (const auto& s: servers) { for (const auto& s: servers) {
if(node == nullptr) { auto node = make_unique<ares_addr_node>();
node = new ares_addr_node();
}
size_t len = net::getBinAddr(&node->addr, s.c_str()); size_t len = net::getBinAddr(&node->addr, s.c_str());
if(len != 0) { if(len != 0) {
node->next = nullptr; node->next = nullptr;
node->family = (len == 4 ? AF_INET : AF_INET6); node->family = (len == 4 ? AF_INET : AF_INET6);
tail->next = node; tail->next = node.release();
tail = node; tail = tail->next;
node = nullptr;
} }
} }
if(node) {
delete node;
}
return root.next; return root.next;
} }

View File

@ -123,7 +123,7 @@ std::unique_ptr<AuthResolver> AuthConfigFactory::createHttpAuthResolver
{ {
std::unique_ptr<AbstractAuthResolver> resolver; std::unique_ptr<AbstractAuthResolver> resolver;
if(op->getAsBool(PREF_NO_NETRC)) { if(op->getAsBool(PREF_NO_NETRC)) {
resolver.reset(new DefaultAuthResolver()); resolver = make_unique<DefaultAuthResolver>();
} else { } else {
auto authResolver = make_unique<NetrcAuthResolver>(); auto authResolver = make_unique<NetrcAuthResolver>();
authResolver->setNetrc(netrc_.get()); authResolver->setNetrc(netrc_.get());
@ -140,7 +140,7 @@ std::unique_ptr<AuthResolver> AuthConfigFactory::createFtpAuthResolver
{ {
std::unique_ptr<AbstractAuthResolver> resolver; std::unique_ptr<AbstractAuthResolver> resolver;
if(op->getAsBool(PREF_NO_NETRC)) { if(op->getAsBool(PREF_NO_NETRC)) {
resolver.reset(new DefaultAuthResolver()); resolver = make_unique<DefaultAuthResolver>();
} else { } else {
auto authResolver = make_unique<NetrcAuthResolver>(); auto authResolver = make_unique<NetrcAuthResolver>();
authResolver->setNetrc(netrc_.get()); authResolver->setNetrc(netrc_.get());

View File

@ -115,7 +115,7 @@ bool BackupIPv4ConnectCommand::execute()
// RFC 6555, the interval will be much longer and around 1 second // RFC 6555, the interval will be much longer and around 1 second
// due to the refresh interval mechanism in DownloadEngine. // due to the refresh interval mechanism in DownloadEngine.
if(startTime_.differenceInMillis(global::wallclock()) >= 300) { if(startTime_.differenceInMillis(global::wallclock()) >= 300) {
socket_.reset(new SocketCore()); socket_ = std::make_shared<SocketCore>();
try { try {
socket_->establishConnection(ipaddr_, port_); socket_->establishConnection(ipaddr_, port_);
e_->addSocketForWriteCheck(socket_, this); e_->addSocketForWriteCheck(socket_, this);

View File

@ -48,34 +48,31 @@ namespace aria2 {
const char BtBitfieldMessage::NAME[] = "bitfield"; const char BtBitfieldMessage::NAME[] = "bitfield";
BtBitfieldMessage::BtBitfieldMessage():SimpleBtMessage(ID, NAME), BtBitfieldMessage::BtBitfieldMessage()
bitfield_(nullptr), : SimpleBtMessage(ID, NAME),
bitfieldLength_(0) bitfieldLength_(0)
{} {}
BtBitfieldMessage::BtBitfieldMessage BtBitfieldMessage::BtBitfieldMessage
(const unsigned char* bitfield, size_t bitfieldLength): (const unsigned char* bitfield, size_t bitfieldLength)
SimpleBtMessage(ID, NAME), : SimpleBtMessage(ID, NAME),
bitfield_(nullptr),
bitfieldLength_(0) bitfieldLength_(0)
{ {
setBitfield(bitfield, bitfieldLength); setBitfield(bitfield, bitfieldLength);
} }
BtBitfieldMessage::~BtBitfieldMessage() BtBitfieldMessage::~BtBitfieldMessage()
{ {}
delete [] bitfield_;
}
void BtBitfieldMessage::setBitfield void BtBitfieldMessage::setBitfield
(const unsigned char* bitfield, size_t bitfieldLength) { (const unsigned char* bitfield, size_t bitfieldLength) {
if(bitfield_ == bitfield) { if(bitfield_.get() == bitfield) {
return; return;
} }
delete [] bitfield_;
bitfieldLength_ = bitfieldLength; bitfieldLength_ = bitfieldLength;
bitfield_ = new unsigned char[bitfieldLength_]; bitfield_ = make_unique<unsigned char[]>(bitfieldLength_);
memcpy(bitfield_, bitfield, bitfieldLength_); memcpy(bitfield_.get(), bitfield, bitfieldLength_);
} }
std::unique_ptr<BtBitfieldMessage> std::unique_ptr<BtBitfieldMessage>
@ -92,9 +89,9 @@ void BtBitfieldMessage::doReceivedAction() {
if(isMetadataGetMode()) { if(isMetadataGetMode()) {
return; return;
} }
getPieceStorage()->updatePieceStats(bitfield_, bitfieldLength_, getPieceStorage()->updatePieceStats(bitfield_.get(), bitfieldLength_,
getPeer()->getBitfield()); getPeer()->getBitfield());
getPeer()->setBitfield(bitfield_, bitfieldLength_); getPeer()->setBitfield(bitfield_.get(), bitfieldLength_);
if(getPeer()->isSeeder() && getPieceStorage()->downloadFinished()) { if(getPeer()->isSeeder() && getPieceStorage()->downloadFinished()) {
throw DL_ABORT_EX(MSG_GOOD_BYE_SEEDER); throw DL_ABORT_EX(MSG_GOOD_BYE_SEEDER);
} }
@ -110,7 +107,7 @@ unsigned char* BtBitfieldMessage::createMessage() {
const size_t msgLength = 5+bitfieldLength_; const size_t msgLength = 5+bitfieldLength_;
auto msg = new unsigned char[msgLength]; auto msg = new unsigned char[msgLength];
bittorrent::createPeerMessageString(msg, msgLength, 1+bitfieldLength_, ID); bittorrent::createPeerMessageString(msg, msgLength, 1+bitfieldLength_, ID);
memcpy(msg+5, bitfield_, bitfieldLength_); memcpy(msg+5, bitfield_.get(), bitfieldLength_);
return msg; return msg;
} }
@ -121,7 +118,7 @@ size_t BtBitfieldMessage::getMessageLength() {
std::string BtBitfieldMessage::toString() const { std::string BtBitfieldMessage::toString() const {
std::string s = NAME; std::string s = NAME;
s += " "; s += " ";
s += util::toHex(bitfield_, bitfieldLength_); s += util::toHex(bitfield_.get(), bitfieldLength_);
return s; return s;
} }

View File

@ -41,7 +41,7 @@ namespace aria2 {
class BtBitfieldMessage : public SimpleBtMessage { class BtBitfieldMessage : public SimpleBtMessage {
private: private:
unsigned char* bitfield_; std::unique_ptr<unsigned char[]> bitfield_;
size_t bitfieldLength_; size_t bitfieldLength_;
public: public:
BtBitfieldMessage(); BtBitfieldMessage();
@ -56,7 +56,7 @@ public:
void setBitfield(const unsigned char* bitfield, size_t bitfieldLength); void setBitfield(const unsigned char* bitfield, size_t bitfieldLength);
const unsigned char* getBitfield() const { return bitfield_; } const unsigned char* getBitfield() const { return bitfield_.get(); }
size_t getBitfieldLength() const { return bitfieldLength_; } size_t getBitfieldLength() const { return bitfieldLength_; }

View File

@ -94,7 +94,7 @@ bool BtDependency::resolve()
std::shared_ptr<RequestGroup> dependee = dependee_; std::shared_ptr<RequestGroup> dependee = dependee_;
// cut reference here // cut reference here
dependee_.reset(); dependee_.reset();
std::shared_ptr<DownloadContext> context(new DownloadContext()); auto context = std::make_shared<DownloadContext>();
try { try {
std::shared_ptr<DiskAdaptor> diskAdaptor = std::shared_ptr<DiskAdaptor> diskAdaptor =
dependee->getPieceStorage()->getDiskAdaptor(); dependee->getPieceStorage()->getDiskAdaptor();

View File

@ -79,7 +79,7 @@ void BtPortMessage::doReceivedAction()
} }
// node id is random at this point. When ping reply received, new DHTNode // node id is random at this point. When ping reply received, new DHTNode
// instance created with proper node ID and is added to a routing table. // instance created with proper node ID and is added to a routing table.
std::shared_ptr<DHTNode> node(new DHTNode()); auto node = std::make_shared<DHTNode>();
node->setIPAddress(getPeer()->getIPAddress()); node->setIPAddress(getPeer()->getIPAddress());
node->setPort(port_); node->setPort(port_);
{ {

View File

@ -217,8 +217,8 @@ void BtSetup::setup(std::vector<std::unique_ptr<Command>>& commands,
(metadataGetMode || !torrentAttrs->privateTorrent)) { (metadataGetMode || !torrentAttrs->privateTorrent)) {
if(!btReg->getLpdMessageReceiver()) { if(!btReg->getLpdMessageReceiver()) {
A2_LOG_INFO("Initializing LpdMessageReceiver."); A2_LOG_INFO("Initializing LpdMessageReceiver.");
std::shared_ptr<LpdMessageReceiver> receiver auto receiver = std::make_shared<LpdMessageReceiver>
(new LpdMessageReceiver(LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT)); (LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT);
bool initialized = false; bool initialized = false;
const std::string& lpdInterface = const std::string& lpdInterface =
e->getOption()->get(PREF_BT_LPD_INTERFACE); e->getOption()->get(PREF_BT_LPD_INTERFACE);
@ -255,11 +255,10 @@ void BtSetup::setup(std::vector<std::unique_ptr<Command>>& commands,
const unsigned char* infoHash = const unsigned char* infoHash =
bittorrent::getInfoHash(requestGroup->getDownloadContext()); bittorrent::getInfoHash(requestGroup->getDownloadContext());
A2_LOG_INFO("Initializing LpdMessageDispatcher."); A2_LOG_INFO("Initializing LpdMessageDispatcher.");
std::shared_ptr<LpdMessageDispatcher> dispatcher auto dispatcher = std::make_shared<LpdMessageDispatcher>
(new LpdMessageDispatcher
(std::string(&infoHash[0], &infoHash[INFO_HASH_LENGTH]), (std::string(&infoHash[0], &infoHash[INFO_HASH_LENGTH]),
btReg->getTcpPort(), btReg->getTcpPort(),
LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT)); LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT);
if(dispatcher->init(btReg->getLpdMessageReceiver()->getLocalAddress(), if(dispatcher->init(btReg->getLpdMessageReceiver()->getLocalAddress(),
/*ttl*/1, /*loop*/1)) { /*ttl*/1, /*loop*/1)) {
A2_LOG_INFO("LpdMessageDispatcher initialized."); A2_LOG_INFO("LpdMessageDispatcher initialized.");

View File

@ -279,9 +279,9 @@ ConsoleStatCalc::ConsoleStatCalc(time_t summaryInterval,
colorOutput_(colorOutput) colorOutput_(colorOutput)
{ {
if(humanReadable) { if(humanReadable) {
sizeFormatter_.reset(new AbbrevSizeFormatter()); sizeFormatter_ = make_unique<AbbrevSizeFormatter>();
} else { } else {
sizeFormatter_.reset(new PlainSizeFormatter()); sizeFormatter_ = make_unique<PlainSizeFormatter>();
} }
} }

View File

@ -63,7 +63,7 @@ private:
time_t summaryInterval_; time_t summaryInterval_;
std::shared_ptr<SizeFormatter> sizeFormatter_; std::unique_ptr<SizeFormatter> sizeFormatter_;
bool readoutVisibility_; bool readoutVisibility_;
bool truncate_; bool truncate_;
bool isTTY_; bool isTTY_;

View File

@ -89,8 +89,8 @@ namespace aria2 {
namespace { namespace {
void showTorrentFile(const std::string& uri) void showTorrentFile(const std::string& uri)
{ {
std::shared_ptr<Option> op(new Option()); auto op = std::make_shared<Option>();
std::shared_ptr<DownloadContext> dctx(new DownloadContext()); auto dctx = std::make_shared<DownloadContext>();
bittorrent::load(uri, dctx, op); bittorrent::load(uri, dctx, op);
bittorrent::print(*global::cout(), dctx); bittorrent::print(*global::cout(), dctx);
} }
@ -154,7 +154,7 @@ Context::Context(bool standalone,
int argc, char** argv, const KeyVals& options) int argc, char** argv, const KeyVals& options)
{ {
std::vector<std::string> args; std::vector<std::string> args;
std::shared_ptr<Option> op(new Option()); auto op = std::make_shared<Option>();
error_code::Value rv; error_code::Value rv;
rv = option_processing(*op.get(), standalone, args, argc, argv, options); rv = option_processing(*op.get(), standalone, args, argc, argv, options);
if(rv != error_code::FINISHED) { if(rv != error_code::FINISHED) {
@ -290,9 +290,8 @@ Context::Context(bool standalone,
!uriListParser) { !uriListParser) {
global::cout()->printf("%s\n", MSG_NO_FILES_TO_DOWNLOAD); global::cout()->printf("%s\n", MSG_NO_FILES_TO_DOWNLOAD);
} else { } else {
reqinfo.reset(new MultiUrlRequestInfo(std::move(requestGroups), reqinfo = std::make_shared<MultiUrlRequestInfo>
op, (std::move(requestGroups), op, uriListParser);
uriListParser));
} }
} }

View File

@ -192,8 +192,8 @@ std::shared_ptr<DHTBucket> DHTBucket::split()
bitfield::flipBit(min_, DHT_ID_LENGTH, prefixLength_); bitfield::flipBit(min_, DHT_ID_LENGTH, prefixLength_);
++prefixLength_; ++prefixLength_;
std::shared_ptr<DHTBucket> rBucket(new DHTBucket(prefixLength_, auto rBucket = std::make_shared<DHTBucket>(prefixLength_, rMax, rMin,
rMax, rMin, localNode_)); localNode_);
std::deque<std::shared_ptr<DHTNode> > lNodes; std::deque<std::shared_ptr<DHTNode> > lNodes;
for(auto & elem : nodes_) { for(auto & elem : nodes_) {
@ -227,7 +227,7 @@ void DHTBucket::getGoodNodes
std::shared_ptr<DHTNode> DHTBucket::getNode(const unsigned char* nodeID, const std::string& ipaddr, uint16_t port) const std::shared_ptr<DHTNode> DHTBucket::getNode(const unsigned char* nodeID, const std::string& ipaddr, uint16_t port) const
{ {
std::shared_ptr<DHTNode> node(new DHTNode(nodeID)); auto node = std::make_shared<DHTNode>(nodeID);
node->setIPAddress(ipaddr); node->setIPAddress(ipaddr);
node->setPort(port); node->setPort(port);
auto itr = auto itr =

View File

@ -63,7 +63,7 @@ void DHTBucketRefreshTask::startup()
b->notifyUpdate(); b->notifyUpdate();
unsigned char targetID[DHT_ID_LENGTH]; unsigned char targetID[DHT_ID_LENGTH];
b->getRandomNodeID(targetID); b->getRandomNodeID(targetID);
std::shared_ptr<DHTNodeLookupTask> task(new DHTNodeLookupTask(targetID)); auto task = std::make_shared<DHTNodeLookupTask>(targetID);
task->setRoutingTable(getRoutingTable()); task->setRoutingTable(getRoutingTable());
task->setMessageDispatcher(getMessageDispatcher()); task->setMessageDispatcher(getMessageDispatcher());
task->setMessageFactory(getMessageFactory()); task->setMessageFactory(getMessageFactory());

View File

@ -48,7 +48,7 @@
namespace aria2 { namespace aria2 {
DHTConnectionImpl::DHTConnectionImpl(int family) DHTConnectionImpl::DHTConnectionImpl(int family)
: socket_(new SocketCore(SOCK_DGRAM)), : socket_(std::make_shared<SocketCore>(SOCK_DGRAM)),
family_(family) family_(family)
{} {}

View File

@ -151,7 +151,7 @@ bool DHTEntryPointNameResolveCommand::execute()
void DHTEntryPointNameResolveCommand::addPingTask void DHTEntryPointNameResolveCommand::addPingTask
(const std::pair<std::string, uint16_t>& addr) (const std::pair<std::string, uint16_t>& addr)
{ {
std::shared_ptr<DHTNode> entryNode(new DHTNode()); auto entryNode = std::make_shared<DHTNode>();
entryNode->setIPAddress(addr.first); entryNode->setIPAddress(addr.first);
entryNode->setPort(addr.second); entryNode->setPort(addr.second);

View File

@ -99,8 +99,7 @@ void DHTPeerAnnounceEntry::getPeers
(std::vector<std::shared_ptr<Peer> >& peers) const (std::vector<std::shared_ptr<Peer> >& peers) const
{ {
for (const auto& p: peerAddrEntries_) { for (const auto& p: peerAddrEntries_) {
std::shared_ptr<Peer> peer(new Peer(p.getIPAddress(), p.getPort())); peers.push_back(std::make_shared<Peer>(p.getIPAddress(), p.getPort()));
peers.push_back(peer);
} }
} }

View File

@ -67,7 +67,7 @@ bool DHTPeerAnnounceStorage::InfoHashLess::operator()
std::shared_ptr<DHTPeerAnnounceEntry> std::shared_ptr<DHTPeerAnnounceEntry>
DHTPeerAnnounceStorage::getPeerAnnounceEntry(const unsigned char* infoHash) DHTPeerAnnounceStorage::getPeerAnnounceEntry(const unsigned char* infoHash)
{ {
std::shared_ptr<DHTPeerAnnounceEntry> entry(new DHTPeerAnnounceEntry(infoHash)); auto entry = std::make_shared<DHTPeerAnnounceEntry>(infoHash);
auto i = entries_.lower_bound(entry); auto i = entries_.lower_bound(entry);
@ -92,7 +92,7 @@ DHTPeerAnnounceStorage::addPeerAnnounce(const unsigned char* infoHash,
bool DHTPeerAnnounceStorage::contains(const unsigned char* infoHash) const bool DHTPeerAnnounceStorage::contains(const unsigned char* infoHash) const
{ {
std::shared_ptr<DHTPeerAnnounceEntry> entry(new DHTPeerAnnounceEntry(infoHash)); auto entry = std::make_shared<DHTPeerAnnounceEntry>(infoHash);
return return
std::binary_search(entries_.begin(), entries_.end(), entry, InfoHashLess()); std::binary_search(entries_.begin(), entries_.end(), entry, InfoHashLess());
} }
@ -100,7 +100,7 @@ bool DHTPeerAnnounceStorage::contains(const unsigned char* infoHash) const
void DHTPeerAnnounceStorage::getPeers(std::vector<std::shared_ptr<Peer> >& peers, void DHTPeerAnnounceStorage::getPeers(std::vector<std::shared_ptr<Peer> >& peers,
const unsigned char* infoHash) const unsigned char* infoHash)
{ {
std::shared_ptr<DHTPeerAnnounceEntry> entry(new DHTPeerAnnounceEntry(infoHash)); auto entry = std::make_shared<DHTPeerAnnounceEntry>(infoHash);
auto i = entries_.find(entry); auto i = entries_.find(entry);
if(i != entries_.end()) { if(i != entries_.end()) {

View File

@ -51,17 +51,15 @@ namespace aria2 {
DHTRoutingTable::DHTRoutingTable(const std::shared_ptr<DHTNode>& localNode) DHTRoutingTable::DHTRoutingTable(const std::shared_ptr<DHTNode>& localNode)
: localNode_(localNode), : localNode_(localNode),
root_(new DHTBucketTreeNode root_(make_unique<DHTBucketTreeNode>
(std::shared_ptr<DHTBucket>(new DHTBucket(localNode_)))), (std::make_shared<DHTBucket>(localNode_))),
numBucket_(1), numBucket_(1),
taskQueue_{nullptr}, taskQueue_{nullptr},
taskFactory_{nullptr} taskFactory_{nullptr}
{} {}
DHTRoutingTable::~DHTRoutingTable() DHTRoutingTable::~DHTRoutingTable()
{ {}
delete root_;
}
bool DHTRoutingTable::addNode(const std::shared_ptr<DHTNode>& node) bool DHTRoutingTable::addNode(const std::shared_ptr<DHTNode>& node)
{ {
@ -80,7 +78,7 @@ bool DHTRoutingTable::addNode(const std::shared_ptr<DHTNode>& node, bool good)
A2_LOG_DEBUG("Adding node with the same ID with localnode is not allowed."); A2_LOG_DEBUG("Adding node with the same ID with localnode is not allowed.");
return false; return false;
} }
DHTBucketTreeNode* treeNode = dht::findTreeNodeFor(root_, node->getID()); auto treeNode = dht::findTreeNodeFor(root_.get(), node->getID());
while(1) { while(1) {
const std::shared_ptr<DHTBucket>& bucket = treeNode->getBucket(); const std::shared_ptr<DHTBucket>& bucket = treeNode->getBucket();
if(bucket->addNode(node)) { if(bucket->addNode(node)) {
@ -112,7 +110,7 @@ void DHTRoutingTable::getClosestKNodes
(std::vector<std::shared_ptr<DHTNode> >& nodes, (std::vector<std::shared_ptr<DHTNode> >& nodes,
const unsigned char* key) const const unsigned char* key) const
{ {
dht::findClosestKNodes(nodes, root_, key); dht::findClosestKNodes(nodes, root_.get(), key);
} }
int DHTRoutingTable::getNumBucket() const int DHTRoutingTable::getNumBucket() const
@ -131,7 +129,7 @@ void DHTRoutingTable::showBuckets() const
std::shared_ptr<DHTBucket> DHTRoutingTable::getBucketFor(const unsigned char* nodeID) const std::shared_ptr<DHTBucket> DHTRoutingTable::getBucketFor(const unsigned char* nodeID) const
{ {
return dht::findBucketFor(root_, nodeID); return dht::findBucketFor(root_.get(), nodeID);
} }
std::shared_ptr<DHTBucket> DHTRoutingTable::getBucketFor(const std::shared_ptr<DHTNode>& node) const std::shared_ptr<DHTBucket> DHTRoutingTable::getBucketFor(const std::shared_ptr<DHTNode>& node) const
@ -163,7 +161,7 @@ void DHTRoutingTable::moveBucketTail(const std::shared_ptr<DHTNode>& node)
void DHTRoutingTable::getBuckets void DHTRoutingTable::getBuckets
(std::vector<std::shared_ptr<DHTBucket> >& buckets) const (std::vector<std::shared_ptr<DHTBucket> >& buckets) const
{ {
dht::enumerateBucket(buckets, root_); dht::enumerateBucket(buckets, root_.get());
} }
void DHTRoutingTable::setTaskQueue(DHTTaskQueue* taskQueue) void DHTRoutingTable::setTaskQueue(DHTTaskQueue* taskQueue)

View File

@ -53,7 +53,7 @@ class DHTRoutingTable {
private: private:
std::shared_ptr<DHTNode> localNode_; std::shared_ptr<DHTNode> localNode_;
DHTBucketTreeNode* root_; std::unique_ptr<DHTBucketTreeNode> root_;
int numBucket_; int numBucket_;

View File

@ -144,7 +144,7 @@ void DHTRoutingTableDeserializer::deserialize(const std::string& filename)
readBytes(fp, buf, buf.size(), 8); readBytes(fp, buf, buf.size(), 8);
// localnode ID // localnode ID
readBytes(fp, buf, buf.size(), DHT_ID_LENGTH); readBytes(fp, buf, buf.size(), DHT_ID_LENGTH);
std::shared_ptr<DHTNode> localNode(new DHTNode(buf)); auto localNode = std::make_shared<DHTNode>(buf);
// 4bytes reserved // 4bytes reserved
readBytes(fp, buf, buf.size(), 4); readBytes(fp, buf, buf.size(), 4);
@ -187,7 +187,7 @@ void DHTRoutingTableDeserializer::deserialize(const std::string& filename)
// node ID // node ID
readBytes(fp, buf, buf.size(), DHT_ID_LENGTH); readBytes(fp, buf, buf.size(), DHT_ID_LENGTH);
std::shared_ptr<DHTNode> node(new DHTNode(buf)); auto node = std::make_shared<DHTNode>(buf);
node->setIPAddress(peer.first); node->setIPAddress(peer.first);
node->setPort(peer.second); node->setPort(peer.second);
// 4bytes reserved // 4bytes reserved

View File

@ -107,7 +107,7 @@ std::vector<std::unique_ptr<Command>> DHTSetup::setup
e); e);
} }
if(!localNode) { if(!localNode) {
localNode.reset(new DHTNode()); localNode = std::make_shared<DHTNode>();
} }
uint16_t port; uint16_t port;

View File

@ -73,7 +73,7 @@ DHTTaskFactoryImpl::createPingTask(const std::shared_ptr<DHTNode>& remoteNode,
std::shared_ptr<DHTTask> std::shared_ptr<DHTTask>
DHTTaskFactoryImpl::createNodeLookupTask(const unsigned char* targetID) DHTTaskFactoryImpl::createNodeLookupTask(const unsigned char* targetID)
{ {
std::shared_ptr<DHTNodeLookupTask> task(new DHTNodeLookupTask(targetID)); auto task = std::make_shared<DHTNodeLookupTask>(targetID);
setCommonProperty(task); setCommonProperty(task);
return task; return task;
} }
@ -81,7 +81,7 @@ DHTTaskFactoryImpl::createNodeLookupTask(const unsigned char* targetID)
std::shared_ptr<DHTTask> std::shared_ptr<DHTTask>
DHTTaskFactoryImpl::createBucketRefreshTask() DHTTaskFactoryImpl::createBucketRefreshTask()
{ {
std::shared_ptr<DHTBucketRefreshTask> task(new DHTBucketRefreshTask()); auto task = std::make_shared<DHTBucketRefreshTask>();
setCommonProperty(task); setCommonProperty(task);
return task; return task;
} }
@ -92,7 +92,7 @@ DHTTaskFactoryImpl::createPeerLookupTask
uint16_t tcpPort, uint16_t tcpPort,
const std::shared_ptr<PeerStorage>& peerStorage) const std::shared_ptr<PeerStorage>& peerStorage)
{ {
std::shared_ptr<DHTPeerLookupTask> task(new DHTPeerLookupTask(ctx, tcpPort)); auto task = std::make_shared<DHTPeerLookupTask>(ctx, tcpPort);
// TODO this may be not freed by RequestGroup::releaseRuntimeResource() // TODO this may be not freed by RequestGroup::releaseRuntimeResource()
task->setPeerStorage(peerStorage); task->setPeerStorage(peerStorage);
setCommonProperty(task); setCommonProperty(task);
@ -110,7 +110,7 @@ std::shared_ptr<DHTTask>
DHTTaskFactoryImpl::createReplaceNodeTask(const std::shared_ptr<DHTBucket>& bucket, DHTTaskFactoryImpl::createReplaceNodeTask(const std::shared_ptr<DHTBucket>& bucket,
const std::shared_ptr<DHTNode>& newNode) const std::shared_ptr<DHTNode>& newNode)
{ {
std::shared_ptr<DHTReplaceNodeTask> task(new DHTReplaceNodeTask(bucket, newNode)); auto task = std::make_shared<DHTReplaceNodeTask>(bucket, newNode);
task->setTimeout(timeout_); task->setTimeout(timeout_);
setCommonProperty(task); setCommonProperty(task);
return task; return task;

View File

@ -164,7 +164,7 @@ DNSCache& DNSCache::operator=(const DNSCache& c)
const std::string& DNSCache::find const std::string& DNSCache::find
(const std::string& hostname, uint16_t port) const (const std::string& hostname, uint16_t port) const
{ {
std::shared_ptr<CacheEntry> target(new CacheEntry(hostname, port)); auto target = std::make_shared<CacheEntry>(hostname, port);
auto i = entries_.find(target); auto i = entries_.find(target);
if(i == entries_.end()) { if(i == entries_.end()) {
return A2STR::NIL; return A2STR::NIL;
@ -176,7 +176,7 @@ const std::string& DNSCache::find
void DNSCache::put void DNSCache::put
(const std::string& hostname, const std::string& ipaddr, uint16_t port) (const std::string& hostname, const std::string& ipaddr, uint16_t port)
{ {
std::shared_ptr<CacheEntry> target(new CacheEntry(hostname, port)); auto target = std::make_shared<CacheEntry>(hostname, port);
auto i = entries_.lower_bound(target); auto i = entries_.lower_bound(target);
if(i != entries_.end() && *(*i) == *target) { if(i != entries_.end() && *(*i) == *target) {
(*i)->add(ipaddr); (*i)->add(ipaddr);
@ -189,7 +189,7 @@ void DNSCache::put
void DNSCache::markBad void DNSCache::markBad
(const std::string& hostname, const std::string& ipaddr, uint16_t port) (const std::string& hostname, const std::string& ipaddr, uint16_t port)
{ {
std::shared_ptr<CacheEntry> target(new CacheEntry(hostname, port)); auto target = std::make_shared<CacheEntry>(hostname, port);
auto i = entries_.find(target); auto i = entries_.find(target);
if(i != entries_.end()) { if(i != entries_.end()) {
(*i)->markBad(ipaddr); (*i)->markBad(ipaddr);
@ -198,7 +198,7 @@ void DNSCache::markBad
void DNSCache::remove(const std::string& hostname, uint16_t port) void DNSCache::remove(const std::string& hostname, uint16_t port)
{ {
std::shared_ptr<CacheEntry> target(new CacheEntry(hostname, port)); auto target = std::make_shared<CacheEntry>(hostname, port);
entries_.erase(target); entries_.erase(target);
} }

View File

@ -210,7 +210,7 @@ std::shared_ptr<UDPTrackerRequest> DefaultBtAnnounce::createUDPTrackerRequest
NetStat& stat = downloadContext_->getNetStat(); NetStat& stat = downloadContext_->getNetStat();
int64_t left = int64_t left =
pieceStorage_->getTotalLength()-pieceStorage_->getCompletedLength(); pieceStorage_->getTotalLength()-pieceStorage_->getCompletedLength();
std::shared_ptr<UDPTrackerRequest> req(new UDPTrackerRequest()); auto req = std::make_shared<UDPTrackerRequest>();
req->remoteAddr = remoteAddr; req->remoteAddr = remoteAddr;
req->remotePort = remotePort; req->remotePort = remotePort;
req->action = UDPT_ACT_ANNOUNCE; req->action = UDPT_ACT_ANNOUNCE;

View File

@ -330,7 +330,7 @@ void DefaultBtProgressInfoFile::load()
if(!(length <= static_cast<uint32_t>(dctx_->getPieceLength()))) { if(!(length <= static_cast<uint32_t>(dctx_->getPieceLength()))) {
throw DL_ABORT_EX(fmt("piece length out of range: %u", length)); throw DL_ABORT_EX(fmt("piece length out of range: %u", length));
} }
std::shared_ptr<Piece> piece(new Piece(index, length)); auto piece = std::make_shared<Piece>(index, length);
uint32_t bitfieldLength; uint32_t bitfieldLength;
READ_CHECK(fp, &bitfieldLength, sizeof(bitfieldLength)); READ_CHECK(fp, &bitfieldLength, sizeof(bitfieldLength));
if(version >= 1) { if(version >= 1) {

View File

@ -76,13 +76,15 @@ namespace aria2 {
DefaultPieceStorage::DefaultPieceStorage DefaultPieceStorage::DefaultPieceStorage
(const std::shared_ptr<DownloadContext>& downloadContext, const Option* option) (const std::shared_ptr<DownloadContext>& downloadContext, const Option* option)
: downloadContext_(downloadContext), : downloadContext_(downloadContext),
bitfieldMan_(new BitfieldMan(downloadContext->getPieceLength(), bitfieldMan_(make_unique<BitfieldMan>
(downloadContext->getPieceLength(),
downloadContext->getTotalLength())), downloadContext->getTotalLength())),
diskWriterFactory_(new DefaultDiskWriterFactory()), diskWriterFactory_(std::make_shared<DefaultDiskWriterFactory>()),
endGame_(false), endGame_(false),
endGamePieceNum_(END_GAME_PIECE_NUM), endGamePieceNum_(END_GAME_PIECE_NUM),
option_(option), option_(option),
pieceStatMan_(new PieceStatMan(downloadContext->getNumPieces(), true)), pieceStatMan_(std::make_shared<PieceStatMan>
(downloadContext->getNumPieces(), true)),
pieceSelector_(make_unique<RarestPieceSelector>(pieceStatMan_)), pieceSelector_(make_unique<RarestPieceSelector>(pieceStatMan_)),
wrDiskCache_(nullptr) wrDiskCache_(nullptr)
{ {
@ -90,20 +92,18 @@ DefaultPieceStorage::DefaultPieceStorage
option_->get(PREF_STREAM_PIECE_SELECTOR); option_->get(PREF_STREAM_PIECE_SELECTOR);
if(pieceSelectorOpt.empty() || pieceSelectorOpt == A2_V_DEFAULT) { if(pieceSelectorOpt.empty() || pieceSelectorOpt == A2_V_DEFAULT) {
streamPieceSelector_ = make_unique<DefaultStreamPieceSelector> streamPieceSelector_ = make_unique<DefaultStreamPieceSelector>
(bitfieldMan_); (bitfieldMan_.get());
} else if(pieceSelectorOpt == V_INORDER) { } else if(pieceSelectorOpt == V_INORDER) {
streamPieceSelector_ = make_unique<InorderStreamPieceSelector> streamPieceSelector_ = make_unique<InorderStreamPieceSelector>
(bitfieldMan_); (bitfieldMan_.get());
} else if(pieceSelectorOpt == A2_V_GEOM) { } else if(pieceSelectorOpt == A2_V_GEOM) {
streamPieceSelector_ = make_unique<GeomStreamPieceSelector> streamPieceSelector_ = make_unique<GeomStreamPieceSelector>
(bitfieldMan_, 1.5); (bitfieldMan_.get(), 1.5);
} }
} }
DefaultPieceStorage::~DefaultPieceStorage() DefaultPieceStorage::~DefaultPieceStorage()
{ {}
delete bitfieldMan_;
}
std::shared_ptr<Piece> DefaultPieceStorage::checkOutPiece std::shared_ptr<Piece> DefaultPieceStorage::checkOutPiece
(size_t index, cuid_t cuid) (size_t index, cuid_t cuid)
@ -112,7 +112,8 @@ std::shared_ptr<Piece> DefaultPieceStorage::checkOutPiece
std::shared_ptr<Piece> piece = findUsedPiece(index); std::shared_ptr<Piece> piece = findUsedPiece(index);
if(!piece) { if(!piece) {
piece.reset(new Piece(index, bitfieldMan_->getBlockLength(index))); piece = std::make_shared<Piece>
(index, bitfieldMan_->getBlockLength(index));
piece->setHashType(downloadContext_->getPieceHashType()); piece->setHashType(downloadContext_->getPieceHashType());
addUsedPiece(piece); addUsedPiece(piece);
@ -138,7 +139,8 @@ std::shared_ptr<Piece> DefaultPieceStorage::getPiece(size_t index)
if(index <= bitfieldMan_->getMaxIndex()) { if(index <= bitfieldMan_->getMaxIndex()) {
piece = findUsedPiece(index); piece = findUsedPiece(index);
if(!piece) { if(!piece) {
piece.reset(new Piece(index, bitfieldMan_->getBlockLength(index))); piece = std::make_shared<Piece>(index,
bitfieldMan_->getBlockLength(index));
if(hasPiece(index)) { if(hasPiece(index)) {
piece->setAllBlock(); piece->setAllBlock();
} }
@ -156,7 +158,7 @@ void DefaultPieceStorage::addUsedPiece(const std::shared_ptr<Piece>& piece)
std::shared_ptr<Piece> DefaultPieceStorage::findUsedPiece(size_t index) const std::shared_ptr<Piece> DefaultPieceStorage::findUsedPiece(size_t index) const
{ {
std::shared_ptr<Piece> p(new Piece()); auto p = std::make_shared<Piece>();
p->setIndex(index); p->setIndex(index);
auto i = usedPieces_.find(p); auto i = usedPieces_.find(p);
@ -769,8 +771,8 @@ void DefaultPieceStorage::markPiecesDone(int64_t length)
} }
size_t r = (length%bitfieldMan_->getBlockLength())/Piece::BLOCK_LENGTH; size_t r = (length%bitfieldMan_->getBlockLength())/Piece::BLOCK_LENGTH;
if(r > 0) { if(r > 0) {
std::shared_ptr<Piece> p auto p = std::make_shared<Piece>(numPiece,
(new Piece(numPiece, bitfieldMan_->getBlockLength(numPiece))); bitfieldMan_->getBlockLength(numPiece));
for(size_t i = 0; i < r; ++i) { for(size_t i = 0; i < r; ++i) {
p->completeBlock(i); p->completeBlock(i);

View File

@ -76,7 +76,7 @@ public:
class DefaultPieceStorage : public PieceStorage { class DefaultPieceStorage : public PieceStorage {
private: private:
std::shared_ptr<DownloadContext> downloadContext_; std::shared_ptr<DownloadContext> downloadContext_;
BitfieldMan* bitfieldMan_; std::unique_ptr<BitfieldMan> bitfieldMan_;
std::shared_ptr<DiskAdaptor> diskAdaptor_; std::shared_ptr<DiskAdaptor> diskAdaptor_;
std::shared_ptr<DiskWriterFactory> diskWriterFactory_; std::shared_ptr<DiskWriterFactory> diskWriterFactory_;
typedef std::set<std::shared_ptr<Piece>, typedef std::set<std::shared_ptr<Piece>,

View File

@ -38,8 +38,7 @@ namespace aria2 {
std::shared_ptr<Exception> DlAbortEx::copy() const std::shared_ptr<Exception> DlAbortEx::copy() const
{ {
std::shared_ptr<Exception> e(new DlAbortEx(*this)); return std::make_shared<DlAbortEx>(*this);
return e;
} }
DlAbortEx::DlAbortEx(const char* file, int line, const std::string& msg): DlAbortEx::DlAbortEx(const char* file, int line, const std::string& msg):

View File

@ -38,8 +38,7 @@ namespace aria2 {
std::shared_ptr<Exception> DlRetryEx::copy() const std::shared_ptr<Exception> DlRetryEx::copy() const
{ {
std::shared_ptr<Exception> e(new DlRetryEx(*this)); return std::make_shared<DlRetryEx>(*this);
return e;
} }
DlRetryEx::DlRetryEx(const char* file, int line, const std::string& msg): DlRetryEx::DlRetryEx(const char* file, int line, const std::string& msg):

View File

@ -100,7 +100,7 @@ DownloadContext::findFileEntryByOffset(int64_t offset) const
return nullptr; return nullptr;
} }
std::shared_ptr<FileEntry> obj(new FileEntry()); auto obj = std::make_shared<FileEntry>();
obj->setOffset(offset); obj->setOffset(offset);
auto i = std::upper_bound(fileEntries_.begin(), fileEntries_.end(), obj, auto i = std::upper_bound(fileEntries_.begin(), fileEntries_.end(), obj,
DerefLess<std::shared_ptr<FileEntry> >()); DerefLess<std::shared_ptr<FileEntry> >());

View File

@ -96,7 +96,7 @@ DownloadEngine::DownloadEngine(std::unique_ptr<EventPoll> eventPoll)
noWait_(true), noWait_(true),
refreshInterval_(DEFAULT_REFRESH_INTERVAL), refreshInterval_(DEFAULT_REFRESH_INTERVAL),
lastRefresh_(0), lastRefresh_(0),
cookieStorage_(new CookieStorage()), cookieStorage_(make_unique<CookieStorage>()),
#ifdef ENABLE_BITTORRENT #ifdef ENABLE_BITTORRENT
btRegistry_(make_unique<BtRegistry>()), btRegistry_(make_unique<BtRegistry>()),
#endif // ENABLE_BITTORRENT #endif // ENABLE_BITTORRENT

View File

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

View File

@ -83,7 +83,7 @@ struct epoll_event EpollEventPoll::KSocketEntry::getEvents()
EpollEventPoll::EpollEventPoll() EpollEventPoll::EpollEventPoll()
: epEventsSize_(EPOLL_EVENTS_MAX), : epEventsSize_(EPOLL_EVENTS_MAX),
epEvents_(new struct epoll_event[epEventsSize_]) epEvents_(make_unique<struct epoll_event[]>(epEventsSize_))
{ {
epfd_ = epoll_create(EPOLL_EVENTS_MAX); epfd_ = epoll_create(EPOLL_EVENTS_MAX);
} }
@ -100,7 +100,6 @@ EpollEventPoll::~EpollEventPoll()
util::safeStrerror(errNum).c_str())); util::safeStrerror(errNum).c_str()));
} }
} }
delete [] epEvents_;
} }
bool EpollEventPoll::good() const bool EpollEventPoll::good() const
@ -114,7 +113,8 @@ void EpollEventPoll::poll(const struct timeval& tv)
int timeout = tv.tv_sec*1000+tv.tv_usec/1000; int timeout = tv.tv_sec*1000+tv.tv_usec/1000;
int res; int res;
while((res = epoll_wait(epfd_, epEvents_, EPOLL_EVENTS_MAX, timeout)) == -1 && while((res = epoll_wait(epfd_, epEvents_.get(),
EPOLL_EVENTS_MAX, timeout)) == -1 &&
errno == EINTR); errno == EINTR);
if(res > 0) { if(res > 0) {
@ -168,7 +168,7 @@ int translateEvents(EventPoll::EventType events)
bool EpollEventPoll::addEvents(sock_t socket, bool EpollEventPoll::addEvents(sock_t socket,
const EpollEventPoll::KEvent& event) const EpollEventPoll::KEvent& event)
{ {
std::shared_ptr<KSocketEntry> socketEntry(new KSocketEntry(socket)); auto socketEntry = std::make_shared<KSocketEntry>(socket);
KSocketEntrySet::iterator i = socketEntries_.lower_bound(socketEntry); KSocketEntrySet::iterator i = socketEntries_.lower_bound(socketEntry);
int r = 0; int r = 0;
int errNum = 0; int errNum = 0;
@ -191,8 +191,7 @@ bool EpollEventPoll::addEvents(sock_t socket,
socketEntries_.insert(i, socketEntry); socketEntries_.insert(i, socketEntry);
if(socketEntries_.size() > epEventsSize_) { if(socketEntries_.size() > epEventsSize_) {
epEventsSize_ *= 2; epEventsSize_ *= 2;
delete [] epEvents_; epEvents_ = make_unique<struct epoll_event[]>(epEventsSize_);
epEvents_ = new struct epoll_event[epEventsSize_];
} }
event.addSelf(socketEntry); event.addSelf(socketEntry);
@ -229,7 +228,7 @@ bool EpollEventPoll::addEvents(sock_t socket, Command* command, int events,
bool EpollEventPoll::deleteEvents(sock_t socket, bool EpollEventPoll::deleteEvents(sock_t socket,
const EpollEventPoll::KEvent& event) const EpollEventPoll::KEvent& event)
{ {
std::shared_ptr<KSocketEntry> socketEntry(new KSocketEntry(socket)); auto socketEntry = std::make_shared<KSocketEntry>(socket);
KSocketEntrySet::iterator i = socketEntries_.find(socketEntry); KSocketEntrySet::iterator i = socketEntries_.find(socketEntry);
if(i == socketEntries_.end()) { if(i == socketEntries_.end()) {
A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", socket)); A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", socket));
@ -285,8 +284,7 @@ bool EpollEventPoll::deleteEvents(sock_t socket, Command* command,
bool EpollEventPoll::addNameResolver bool EpollEventPoll::addNameResolver
(const std::shared_ptr<AsyncNameResolver>& resolver, Command* command) (const std::shared_ptr<AsyncNameResolver>& resolver, Command* command)
{ {
std::shared_ptr<KAsyncNameResolverEntry> entry auto entry = std::make_shared<KAsyncNameResolverEntry>(resolver, command);
(new KAsyncNameResolverEntry(resolver, command));
KAsyncNameResolverEntrySet::iterator itr = KAsyncNameResolverEntrySet::iterator itr =
nameResolverEntries_.lower_bound(entry); nameResolverEntries_.lower_bound(entry);
if(itr != nameResolverEntries_.end() && *(*itr) == *entry) { if(itr != nameResolverEntries_.end() && *(*itr) == *entry) {
@ -301,8 +299,7 @@ bool EpollEventPoll::addNameResolver
bool EpollEventPoll::deleteNameResolver bool EpollEventPoll::deleteNameResolver
(const std::shared_ptr<AsyncNameResolver>& resolver, Command* command) (const std::shared_ptr<AsyncNameResolver>& resolver, Command* command)
{ {
std::shared_ptr<KAsyncNameResolverEntry> entry auto entry = std::make_shared<KAsyncNameResolverEntry>(resolver, command);
(new KAsyncNameResolverEntry(resolver, command));
KAsyncNameResolverEntrySet::iterator itr = KAsyncNameResolverEntrySet::iterator itr =
nameResolverEntries_.find(entry); nameResolverEntries_.find(entry);
if(itr == nameResolverEntries_.end()) { if(itr == nameResolverEntries_.end()) {

View File

@ -84,7 +84,7 @@ private:
size_t epEventsSize_; size_t epEventsSize_;
struct epoll_event* epEvents_; std::unique_ptr<struct epoll_event[]> epEvents_;
static const size_t EPOLL_EVENTS_MAX = 1024; static const size_t EPOLL_EVENTS_MAX = 1024;

View File

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

View File

@ -158,7 +158,7 @@ FileEntry::getRequest
if(uri.empty()) { if(uri.empty()) {
break; break;
} }
req.reset(new Request()); req = std::make_shared<Request>();
if(req->setUri(uri)) { if(req->setUri(uri)) {
if(std::count(inFlightHosts.begin(), if(std::count(inFlightHosts.begin(),
inFlightHosts.end(),req->getHost()) inFlightHosts.end(),req->getHost())
@ -293,7 +293,7 @@ FileEntry::findFasterRequest
} }
if(!fastCands.empty()) { if(!fastCands.empty()) {
std::sort(fastCands.begin(), fastCands.end(), ServerStatFaster()); std::sort(fastCands.begin(), fastCands.end(), ServerStatFaster());
std::shared_ptr<Request> fastestRequest(new Request()); auto fastestRequest = std::make_shared<Request>();
const std::string& uri = fastCands.front().second; const std::string& uri = fastCands.front().second;
A2_LOG_DEBUG(fmt("Selected %s from fastCands", uri.c_str())); A2_LOG_DEBUG(fmt("Selected %s from fastCands", uri.c_str()));
// Candidate URIs where already parsed when populating fastCands. // Candidate URIs where already parsed when populating fastCands.

View File

@ -203,7 +203,7 @@ std::shared_ptr<SocketCore> FtpConnection::createServerSocket()
{ {
std::pair<std::string, uint16_t> addrinfo; std::pair<std::string, uint16_t> addrinfo;
socket_->getAddrInfo(addrinfo); socket_->getAddrInfo(addrinfo);
std::shared_ptr<SocketCore> serverSocket(new SocketCore()); auto serverSocket = std::make_shared<SocketCore>();
serverSocket->bind(addrinfo.first.c_str(), 0, AF_UNSPEC); serverSocket->bind(addrinfo.first.c_str(), 0, AF_UNSPEC);
serverSocket->beginListen(); serverSocket->beginListen();
return serverSocket; return serverSocket;

View File

@ -58,8 +58,7 @@ FtpDownloadCommand::FtpDownloadCommand
const std::shared_ptr<SocketCore>& dataSocket, const std::shared_ptr<SocketCore>& dataSocket,
const std::shared_ptr<SocketCore>& ctrlSocket) const std::shared_ptr<SocketCore>& ctrlSocket)
:DownloadCommand(cuid, req, fileEntry, requestGroup, e, dataSocket, :DownloadCommand(cuid, req, fileEntry, requestGroup, e, dataSocket,
std::shared_ptr<SocketRecvBuffer> std::make_shared<SocketRecvBuffer>(dataSocket)),
(new SocketRecvBuffer(dataSocket))),
ftpConnection_(ftpConnection), ftpConnection_(ftpConnection),
ctrlSocket_(ctrlSocket) {} ctrlSocket_(ctrlSocket) {}

View File

@ -113,13 +113,9 @@ std::unique_ptr<Command> FtpInitiateConnectionCommand::createNextCommandProxied
if(proxyMethod == V_GET) { if(proxyMethod == V_GET) {
// Use GET for FTP via HTTP proxy. // Use GET for FTP via HTTP proxy.
getRequest()->setMethod(Request::METHOD_GET); getRequest()->setMethod(Request::METHOD_GET);
std::shared_ptr<HttpRequestConnectChain> chain c->setControlChain(std::make_shared<HttpRequestConnectChain>());
(new HttpRequestConnectChain());
c->setControlChain(chain);
} else if(proxyMethod == V_TUNNEL) { } else if(proxyMethod == V_TUNNEL) {
std::shared_ptr<FtpTunnelRequestConnectChain> chain c->setControlChain(std::make_shared<FtpTunnelRequestConnectChain>());
(new FtpTunnelRequestConnectChain());
c->setControlChain(chain);
} else { } else {
// Unreachable // Unreachable
assert(0); assert(0);
@ -150,10 +146,9 @@ std::unique_ptr<Command> FtpInitiateConnectionCommand::createNextCommandProxied
// Use GET for FTP via HTTP proxy. // Use GET for FTP via HTTP proxy.
getRequest()->setMethod(Request::METHOD_GET); getRequest()->setMethod(Request::METHOD_GET);
std::shared_ptr<SocketRecvBuffer> socketRecvBuffer auto socketRecvBuffer = std::make_shared<SocketRecvBuffer>(pooledSocket);
(new SocketRecvBuffer(pooledSocket)); auto hc = std::make_shared<HttpConnection>(getCuid(), pooledSocket,
std::shared_ptr<HttpConnection> hc socketRecvBuffer);
(new HttpConnection(getCuid(), pooledSocket, socketRecvBuffer));
auto c = make_unique<HttpRequestCommand>(getCuid(), auto c = make_unique<HttpRequestCommand>(getCuid(),
getRequest(), getRequest(),
@ -191,9 +186,8 @@ std::unique_ptr<Command> FtpInitiateConnectionCommand::createNextCommandPlain
getRequestGroup(), getRequestGroup(),
getDownloadEngine(), getDownloadEngine(),
getSocket()); getSocket());
std::shared_ptr<FtpNegotiationConnectChain> chain
(new FtpNegotiationConnectChain()); c->setControlChain(std::make_shared<FtpNegotiationConnectChain>());
c->setControlChain(chain);
setupBackupConnection(hostname, addr, port, c.get()); setupBackupConnection(hostname, addr, port, c.get());
return std::move(c); return std::move(c);
} }

View File

@ -90,7 +90,8 @@ FtpNegotiationCommand::FtpNegotiationCommand
const std::string& baseWorkingDir): const std::string& baseWorkingDir):
AbstractCommand(cuid, req, fileEntry, requestGroup, e, socket), AbstractCommand(cuid, req, fileEntry, requestGroup, e, socket),
sequence_(seq), sequence_(seq),
ftp_(new FtpConnection(cuid, socket, req, ftp_(std::make_shared<FtpConnection>
(cuid, socket, req,
e->getAuthConfigFactory()->createAuthConfig e->getAuthConfigFactory()->createAuthConfig
(req, requestGroup->getOption().get()), (req, requestGroup->getOption().get()),
getOption().get())), getOption().get())),
@ -447,9 +448,8 @@ bool FtpNegotiationCommand::onFileSizeDetermined(int64_t totalLength)
getSegmentMan()->getSegmentWithIndex(getCuid(), 0); getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
return true; return true;
} else { } else {
std::shared_ptr<BtProgressInfoFile> progressInfoFile auto progressInfoFile = std::make_shared<DefaultBtProgressInfoFile>
(new DefaultBtProgressInfoFile (getDownloadContext(), nullptr, getOption().get());
(getDownloadContext(), std::shared_ptr<PieceStorage>(), getOption().get()));
getRequestGroup()->adjustFilename(progressInfoFile); getRequestGroup()->adjustFilename(progressInfoFile);
getRequestGroup()->initPieceStorage(); getRequestGroup()->initPieceStorage();
@ -664,7 +664,7 @@ bool FtpNegotiationCommand::preparePasvConnect() {
getCuid(), getCuid(),
dataAddr.first.c_str(), dataAddr.first.c_str(),
pasvPort_)); pasvPort_));
dataSocket_.reset(new SocketCore()); dataSocket_ = std::make_shared<SocketCore>();
dataSocket_->establishConnection(dataAddr.first, pasvPort_, false); dataSocket_->establishConnection(dataAddr.first, pasvPort_, false);
disableReadCheckSocket(); disableReadCheckSocket();
setWriteCheckSocket(dataSocket_); setWriteCheckSocket(dataSocket_);
@ -685,13 +685,13 @@ bool FtpNegotiationCommand::resolveProxy()
A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER, A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER,
getCuid(), getCuid(),
proxyAddr_.c_str(), proxyReq->getPort())); proxyAddr_.c_str(), proxyReq->getPort()));
dataSocket_.reset(new SocketCore()); dataSocket_ = std::make_shared<SocketCore>();
dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort()); dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort());
disableReadCheckSocket(); disableReadCheckSocket();
setWriteCheckSocket(dataSocket_); setWriteCheckSocket(dataSocket_);
std::shared_ptr<SocketRecvBuffer> socketRecvBuffer auto socketRecvBuffer = std::make_shared<SocketRecvBuffer>(dataSocket_);
(new SocketRecvBuffer(dataSocket_)); http_ = std::make_shared<HttpConnection>(getCuid(), dataSocket_,
http_.reset(new HttpConnection(getCuid(), dataSocket_, socketRecvBuffer)); socketRecvBuffer);
sequence_ = SEQ_SEND_TUNNEL_REQUEST; sequence_ = SEQ_SEND_TUNNEL_REQUEST;
return false; return false;
} }
@ -728,7 +728,7 @@ bool FtpNegotiationCommand::sendTunnelRequest()
} }
auto httpRequest = make_unique<HttpRequest>(); auto httpRequest = make_unique<HttpRequest>();
httpRequest->setUserAgent(getOption()->get(PREF_USER_AGENT)); httpRequest->setUserAgent(getOption()->get(PREF_USER_AGENT));
std::shared_ptr<Request> req(new Request()); auto req = std::make_shared<Request>();
// Construct fake URI in order to use HttpRequest // Construct fake URI in order to use HttpRequest
std::pair<std::string, uint16_t> dataAddr; std::pair<std::string, uint16_t> dataAddr;
uri::UriStruct us; uri::UriStruct us;

View File

@ -79,7 +79,7 @@ HttpSkipResponseCommand::HttpSkipResponseCommand
receivedBytes_(0), receivedBytes_(0),
httpConnection_(httpConnection), httpConnection_(httpConnection),
httpResponse_(std::move(httpResponse)), httpResponse_(std::move(httpResponse)),
streamFilter_(new NullSinkStreamFilter()) streamFilter_(make_unique<NullSinkStreamFilter>())
{ {
checkSocketRecvBuffer(); checkSocketRecvBuffer();
} }