Update string_format template to use std::nothrow and OSFatal on error

This commit is contained in:
Maschell 2022-05-08 19:30:17 +02:00
parent 0eab0261b1
commit 58fbfc270b
2 changed files with 12 additions and 1 deletions

View File

@ -1,6 +1,7 @@
#pragma once
#include "logger.h"
#include "utils.h"
#include <memory>
#include <string>
#include <vector>
@ -10,7 +11,12 @@ template<typename... Args>
std::string string_format(const std::string &format, Args... args) {
int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0'
auto size = static_cast<size_t>(size_s);
auto buf = std::make_unique<char[]>(size);
auto buf = make_unique_nothrow<char[]>(size);
if (!buf) {
DEBUG_FUNCTION_LINE_ERR("string_format failed, not enough memory");
OSFatal("string_format failed, not enough memory");
return std::string("");
}
std::snprintf(buf.get(), size, format.c_str(), args...);
return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
}

View File

@ -11,6 +11,11 @@ std::unique_ptr<T> make_unique_nothrow(Args &&...args) noexcept(noexcept(T(std::
return std::unique_ptr<T>(new (std::nothrow) T(std::forward<Args>(args)...));
}
template<typename T>
inline typename std::_MakeUniq<T>::__array make_unique_nothrow(size_t num) noexcept {
return std::unique_ptr<T>(new (std::nothrow) std::remove_extent_t<T>[num]());
}
template<class T, class... Args>
std::shared_ptr<T> make_shared_nothrow(Args &&...args) noexcept(noexcept(T(std::forward<Args>(args)...))) {
return std::shared_ptr<T>(new (std::nothrow) T(std::forward<Args>(args)...));