Startup returns a unique_ptr instead of using a static
This commit is contained in:
@@ -3,11 +3,23 @@
|
||||
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
|
||||
namespace aocpp {
|
||||
|
||||
auto Startup(int argc, char ** argv) -> std::istream&;
|
||||
class ConditionalDeleter {
|
||||
bool should_delete_;
|
||||
|
||||
public:
|
||||
ConditionalDeleter(bool should_delete) : should_delete_ {should_delete} {}
|
||||
|
||||
template <typename T>
|
||||
auto operator()(T * pointer) -> void { if (should_delete_) { delete pointer; }}
|
||||
};
|
||||
|
||||
auto Startup(int argc, char ** argv) -> std::unique_ptr<std::istream, ConditionalDeleter>;
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
|
@@ -12,19 +12,25 @@
|
||||
|
||||
namespace aocpp {
|
||||
|
||||
auto Startup(int argc, char ** argv) -> std::istream& {
|
||||
if (std::getenv("DOCTEST")) {
|
||||
exit(doctest::Context{argc, argv}.run());
|
||||
}
|
||||
auto Startup(int argc, char ** argv) -> std::unique_ptr<std::istream, ConditionalDeleter> {
|
||||
bool should_delete;
|
||||
std::istream* result_ptr;
|
||||
|
||||
static std::ifstream fin;
|
||||
switch (argc) {
|
||||
case 2: fin = std::ifstream{argv[1]}; return fin;
|
||||
case 1: return std::cin;
|
||||
default:
|
||||
std::cerr << "bad arguments\n";
|
||||
exit(EXIT_FAILURE);
|
||||
case 2:
|
||||
should_delete = true;
|
||||
result_ptr = new std::ifstream{argv[1]};
|
||||
break;
|
||||
case 1:
|
||||
should_delete = false;
|
||||
result_ptr = &std::cin;
|
||||
break;
|
||||
default:
|
||||
std::cerr << "bad arguments\n";
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
return {result_ptr, should_delete};
|
||||
}
|
||||
|
||||
}
|
||||
|
Reference in New Issue
Block a user