1

clean moved objects, destructor

This commit is contained in:
2022-07-20 22:03:39 +02:00
parent b2dfa72f3b
commit f420d5f677

View File

@ -72,7 +72,8 @@ public:
while (current != nullptr) { while (current != nullptr) {
next = current->next; next = current->next;
delete current; ((Type)*current).~Type(); // Object
delete current; // Wrapper
current = next; current = next;
} }
} }
@ -85,6 +86,7 @@ public:
return Iterator(tail->next); return Iterator(tail->next);
} }
// NOTE: Insert copies
unsigned int insert_at(Type e, unsigned int i) override { unsigned int insert_at(Type e, unsigned int i) override {
if (i > size()) { if (i > size()) {
return -1; return -1;
@ -150,6 +152,7 @@ public:
return size(); return size();
} }
// NOTE: Remove moves
std::optional<Type> remove_at(unsigned int i) override { std::optional<Type> remove_at(unsigned int i) override {
if (empty() || i >= size()) { if (empty() || i >= size()) {
return std::nullopt; return std::nullopt;
@ -168,14 +171,15 @@ public:
return std::nullopt; return std::nullopt;
} }
Type ret = *e; Type ret = std::move(*e);
((Type)*e).~Type(); // Cleanup rest of the move
// Remove the wrapper
e->next->prev = e->prev; e->next->prev = e->prev;
e->prev->next = e->next; e->prev->next = e->next;
delete e; delete e;
num_elements = num_elements - 1;
num_elements = num_elements - 1;
return ret; return ret;
} }
@ -184,19 +188,20 @@ public:
return std::nullopt; return std::nullopt;
} }
Type e = *head; Type e = std::move(*head);
WrapperType* old_head = head; ((Type)*head).~Type(); // Cleanup rest of the move
// Remove wrapper
WrapperType* old_head = head;
head = head->next; head = head->next;
if (head != nullptr) { if (head != nullptr) {
head->prev = nullptr; head->prev = nullptr;
} else { } else {
tail = nullptr; tail = nullptr;
} }
delete old_head; delete old_head;
num_elements = num_elements - 1;
num_elements = num_elements - 1;
return e; return e;
} }
@ -205,19 +210,20 @@ public:
return std::nullopt; return std::nullopt;
} }
Type e = *tail; Type e = std::move(*tail);
WrapperType* old_tail = tail; ((Type)*tail).~Type(); // Cleanup rest of the move
// Remove wrapper
WrapperType* old_tail = tail;
tail = tail->prev; tail = tail->prev;
if (tail != nullptr) { if (tail != nullptr) {
tail->next = nullptr; tail->next = nullptr;
} else { } else {
head = nullptr; head = nullptr;
} }
delete old_tail; delete old_tail;
num_elements = num_elements - 1;
num_elements = num_elements - 1;
return e; return e;
} }
@ -280,7 +286,7 @@ public:
void print(OutStream& out) const override { void print(OutStream& out) const override {
// Our stream cannot print all types so enable this only for debugging purposes (only int) // Our stream cannot print all types so enable this only for debugging purposes (only int)
if constexpr (std::is_same<Type, int>::value) { if constexpr (std::is_same_v<Type, int>) {
if (empty()) { if (empty()) {
out << "Print List (0 elements)" << endl; out << "Print List (0 elements)" << endl;
return; return;