Skip to content

Commit

Permalink
Use std::make_unique (#2736)
Browse files Browse the repository at this point in the history
This PR improves use of `std::unique_ptr` by using `std::make_unique` where appropriate instead of `reset()`, and also updating some class constructors to use direct assignment.

https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#r23-use-make_unique-to-make-unique_ptrs

* Use `std::make_unique` and assignment instead of reset()
* Revert changes where allocations shouldn't be default-initialised
  • Loading branch information
mikee47 authored Mar 18, 2024
1 parent b9029a2 commit 07cd096
Show file tree
Hide file tree
Showing 25 changed files with 56 additions and 61 deletions.
2 changes: 1 addition & 1 deletion Sming/Arch/Esp32/Services/Profiling/TaskStat.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ struct TaskStat::Info {
TaskStat::TaskStat(Print& out) : out(out)
{
#if CONFIG_FREERTOS_USE_TRACE_FACILITY && CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS
taskInfo.reset(new Info[2]);
taskInfo = std::make_unique<Info[]>(2);
#endif
}

Expand Down
2 changes: 1 addition & 1 deletion Sming/Arch/Host/Components/driver/hw_timer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ static std::unique_ptr<CTimerThread> timer1;

void hw_timer_init(void)
{
timer1.reset(new CTimerThread("Timer1"));
timer1 = std::make_unique<CTimerThread>("Timer1");
}

void hw_timer_cleanup()
Expand Down
6 changes: 3 additions & 3 deletions Sming/Arch/Host/Components/driver/uart_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -170,9 +170,9 @@ void startup(const Config& config)

auto& server = servers[i];
if(devname == nullptr) {
server.reset(new CUartPort(i));
server = std::make_unique<CUartPort>(i);
} else {
server.reset(new CUartDevice(i, devname, config.baud[i]));
server = std::make_unique<CUartDevice>(i, devname, config.baud[i]);
}
server->execute();
}
Expand Down Expand Up @@ -450,7 +450,7 @@ void* CUartDevice::thread_routine()
while(!done) {
if(txsem.timedwait(IDLE_SLEEP_MS * 1000)) {
if(uart != nullptr && !device) {
device.reset(new SerialDevice);
device = std::make_unique<SerialDevice>();
char res = device->openDevice(deviceName, uart->baud_rate);
if(res != 1) {
host_debug_e("UART%u error %d opening serial device '%s'", uart_nr, res, deviceName);
Expand Down
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ extern void ets_wdt_enable(void);
extern void ets_wdt_disable(void);
extern void wdt_feed(void);


/** @brief Disable interrupts
* @retval Current interrupt level
* @note Hardware timer is unaffected if operating in non-maskable mode
Expand Down
12 changes: 6 additions & 6 deletions Sming/Arch/Rp2040/Components/rp2040/src/tasks.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@
#include <pico/util/queue.h>
#include <sming_attr.h>

namespace {

namespace
{
class TaskQueue
{
public:
static void init()
{
spinlock = spin_lock_claim_unused(true);
spinlock = spin_lock_claim_unused(true);
}

TaskQueue(os_task_t callback, uint8_t length): callback(callback)
TaskQueue(os_task_t callback, uint8_t length) : callback(callback)
{
queue_init_with_spinlock(&queue, sizeof(os_event_t), length, spinlock);
}
Expand All @@ -26,7 +26,7 @@ class TaskQueue

bool __forceinline post(os_signal_t sig, os_param_t par)
{
os_event_t event {sig, par};
os_event_t event{sig, par};
return queue_try_add(&queue, &event);
}

Expand Down Expand Up @@ -60,7 +60,7 @@ const uint8_t SYSTEM_TASK_QUEUE_LENGTH = 8;

TaskQueue* task_queues[SYSTEM_TASK_PRIO + 1];

};
}; // namespace

bool system_os_task(os_task_t callback, os_task_priority_t prio, os_event_t* events, uint8_t qlen)
{
Expand Down
50 changes: 25 additions & 25 deletions Sming/Arch/Rp2040/Components/rp2040/src/wifi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,46 +19,45 @@ extern "C" {
IMPORT_FSTR_ARRAY_LOCAL(cyw43_firmware, uint8_t, CYW43_FIRMWARE)
#endif

namespace {

namespace
{
#define BUFFER_SIZE 16384
#define DICT_SIZE 32767

class Decompressor {
class Decompressor
{
public:
explicit Decompressor(const FSTR::ObjectBase& data)
explicit Decompressor(const FSTR::ObjectBase& data) : stream(new FlashMemoryStream(data))
{
stream.reset(new FlashMemoryStream(data));
}

explicit Decompressor(Storage::Partition part)
explicit Decompressor(Storage::Partition part) : stream(new Storage::PartitionStream(part))
{
stream.reset(new Storage::PartitionStream(part));
}

bool init()
{
uzlib_init();
uzlib_uncompress_init(&state, dict, DICT_SIZE);
state.source_read_cb = read_source;
int res = uzlib_gzip_parse_header(&state);
if (res != TINF_OK) {
int res = uzlib_gzip_parse_header(&state);
if(res != TINF_OK) {
debug_e("[CYW] bad GZIP header %d", res);
return false;
}
return true;
return true;
}

bool read(void* dest, size_t length)
{
state.dest = static_cast<uint8_t*>(dest);
state.dest_limit = state.dest + length;
int res = uzlib_uncompress_chksum(&state);
state.dest = static_cast<uint8_t*>(dest);
state.dest_limit = state.dest + length;
int res = uzlib_uncompress_chksum(&state);
if(res != TINF_OK) {
debug_e("[CYW] Decompress error %d", res);
return false;
}
return true;
return true;
}

private:
Expand All @@ -77,35 +76,36 @@ class Decompressor {
return *self->state.source++;
}

struct uzlib_uncomp state{};
struct uzlib_uncomp state {
};
uint8_t src_buffer[BUFFER_SIZE]{};
uint8_t dict[DICT_SIZE];
uint8_t dict[DICT_SIZE];
std::unique_ptr<IDataSourceStream> stream;
};

std::unique_ptr<Decompressor> decompressor;

}
} // namespace

int cyw43_storage_init()
{
#ifdef CYW43_FIRMWARE
decompressor.reset(new Decompressor(cyw43_firmware));
decompressor = std::make_unique<Decompressor>(cyw43_firmware);
#else
auto part = Storage::findPartition("cyw43_fw");
if(!part) {
debug_e("Failed to find CYW43 firmware partition");
} else {
decompressor.reset(new Decompressor(part));
decompressor = std::make_unique<Decompressor>(part);
}
#endif

if (!decompressor || !decompressor->init()) {
if(!decompressor || !decompressor->init()) {
decompressor.reset();
return -1;
}
return -1;
}

return 0;
return 0;
}

uint32_t cyw43_storage_read(void* dest, uint32_t length)
Expand All @@ -117,9 +117,9 @@ uint32_t cyw43_storage_read(void* dest, uint32_t length)
if(!decompressor->read(dest, length)) {
decompressor.reset();
return 0;
}
}

return length;
return length;
}

void cyw43_storage_cleanup()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,9 @@ namespace Transport
class TcpClientTransport : public TcpTransport
{
public:
TcpClientTransport(TcpClient& client)
TcpClientTransport(TcpClient& client) : stream(new TcpClientStream(client))
{
client.setReceiveDelegate(TcpClientDataDelegate(&TcpClientTransport::process, this));
stream.reset(new TcpClientStream(client));
}

protected:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,7 @@ bool StationImpl::smartConfigStart(SmartConfigType sctype, SmartConfigDelegate c
return false;
}

smartConfigEventInfo.reset(new SmartConfigEventInfo{});
smartConfigEventInfo = std::make_unique<SmartConfigEventInfo>();
if(!smartConfigEventInfo) {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ bool AccessPointImpl::config(const String& ssid, String password, AUTH_MODE mode
debugf("AP configuration was updated");
} else {
debugf("Set AP configuration in background");
runConfig.reset(new softap_config(config));
runConfig = std::make_unique<softap_config>(config);
}
} else {
debugf("AP configuration loaded");
Expand Down
5 changes: 2 additions & 3 deletions Sming/Components/rboot/include/Network/RbootHttpUpdater.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,14 @@ class RbootHttpUpdater : protected HttpClient
std::unique_ptr<RbootOutputStream> stream; // (optional) output stream to use.

Item(String url, uint32_t targetOffset, size_t size, RbootOutputStream* stream)
: url(url), targetOffset(targetOffset), size(size)
: url(url), targetOffset(targetOffset), size(size), stream(stream)
{
this->stream.reset(stream);
}

RbootOutputStream* getStream()
{
if(!stream) {
stream.reset(new RbootOutputStream(targetOffset, size));
stream = std::make_unique<RbootOutputStream>(targetOffset, size);
}
return stream.get();
}
Expand Down
2 changes: 1 addition & 1 deletion Sming/Components/ssl/Axtls/AxConnection.h
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class AxConnection : public Connection
const Certificate* getCertificate() const override
{
if(!certificate && ssl->x509_ctx != nullptr) {
certificate.reset(new AxCertificate(ssl));
certificate = std::make_unique<AxCertificate>(ssl);
}

return certificate.get();
Expand Down
4 changes: 2 additions & 2 deletions Sming/Components/ssl/BearSsl/BrClientConnection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ void BrClientConnection::startCert(uint32_t length)
return;
}

certificate.reset(new BrCertificate);
x509Decoder.reset(new X509Decoder(&certificate->subject, &certificate->issuer));
certificate = std::make_unique<BrCertificate>();
x509Decoder = std::make_unique<X509Decoder>(&certificate->subject, &certificate->issuer);

auto& types = context.session.validators.fingerprintTypes;
resetHash(certSha1Context, types.contains(Fingerprint::Type::CertSha1));
Expand Down
2 changes: 1 addition & 1 deletion Sming/Components/ssl/src/Session.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ void Session::handshakeComplete(bool success)
// If requested, take a copy of the session ID for later re-use
if(options.sessionResume) {
if(!sessionId) {
sessionId.reset(new SessionId);
sessionId = std::make_unique<SessionId>();
}
*sessionId = connection->getSessionId();
}
Expand Down
3 changes: 1 addition & 2 deletions Sming/Core/Data/CsvReader.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,9 @@ class CsvReader
*/
CsvReader(IDataSourceStream* source, char fieldSeparator = ',', const CStringArray& headings = nullptr,
size_t maxLineLength = 2048)
: fieldSeparator(fieldSeparator), userHeadingsProvided(headings), maxLineLength(maxLineLength),
: source(source), fieldSeparator(fieldSeparator), userHeadingsProvided(headings), maxLineLength(maxLineLength),
headings(headings)
{
this->source.reset(source);
reset();
}

Expand Down
2 changes: 1 addition & 1 deletion Sming/Core/Data/Stream/EndlessMemoryStream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ bool EndlessMemoryStream::seek(int len)
size_t EndlessMemoryStream::write(const uint8_t* buffer, size_t size)
{
if(!stream) {
stream.reset(new MemoryDataStream());
stream = std::make_unique<MemoryDataStream>();
}

return stream->write(buffer, size);
Expand Down
2 changes: 1 addition & 1 deletion Sming/Core/Data/Stream/SectionStream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ void SectionStream::scanSource(uint8_t maxSections)
constexpr size_t bufSize{512};
char buffer[bufSize];

sections.reset(new Section[maxSections]{});
sections = std::make_unique<Section[]>(maxSections);

size_t offset{0};
while(sectionCount < maxSections && !stream->isFinished()) {
Expand Down
2 changes: 1 addition & 1 deletion Sming/Libraries/DiskStorage
2 changes: 1 addition & 1 deletion Sming/Libraries/HardwareSPI
2 changes: 1 addition & 1 deletion Sming/Libraries/IOControl
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class HttpUpgrader : protected HttpClient
ReadWriteStream* getStream()
{
if(!stream) {
stream.reset(new Ota::UpgradeOutputStream(partition));
stream = std::make_unique<Ota::UpgradeOutputStream>(partition);
}
return stream.get();
}
Expand Down
2 changes: 1 addition & 1 deletion Sming/Libraries/Yeelight/YeelightBulb.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ bool YeelightBulb::connect()
return true;
}

connection.reset(new TcpClient(TcpClientDataDelegate(&YeelightBulb::onResponse, this)));
connection = std::make_unique<TcpClient>(TcpClientDataDelegate(&YeelightBulb::onResponse, this));

connection->setTimeOut(USHRT_MAX); // Stay connected forever

Expand Down
2 changes: 1 addition & 1 deletion samples/Basic_Audio/app/application.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ static struct {
Serial << _F("Generating sine wave table @ ") << frequency << _F(" Hz, ") << sampleCount << _F(" samples")
<< endl;

samples.reset(new uint16_t[sampleCount]);
samples = std::make_unique<uint16_t[]>(sampleCount);
if(!samples) {
debug_e("Memory allocation failed");
return false;
Expand Down
2 changes: 1 addition & 1 deletion samples/Basic_Ota/app/application.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ void doUpgrade()
Serial.println(F("Updating..."));

// need a clean object, otherwise if run before and failed will not run again
otaUpdater.reset(new Ota::Network::HttpUpgrader);
otaUpdater = std::make_unique<Ota::Network::HttpUpgrader>();

// select rom slot to flash
auto part = ota.getNextBootPartition();
Expand Down
3 changes: 1 addition & 2 deletions samples/Basic_Serial/include/SerialTransmitDemo.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@
class SerialTransmitDemo
{
public:
SerialTransmitDemo(HardwareSerial& serial, IDataSourceStream* stream) : serial(serial)
SerialTransmitDemo(HardwareSerial& serial, IDataSourceStream* stream) : serial(serial), stream(stream)
{
this->stream.reset(stream);
serial.onTransmitComplete(TransmitCompleteDelegate(&SerialTransmitDemo::onTransmitComplete, this));
}

Expand Down

0 comments on commit 07cd096

Please sign in to comment.