In low-latency systems, achieving minimal overhead and maximizing performance is crucial. Intrusive containers allow objects to manage their own storage, significantly reducing the overhead associated with dynamic memory allocation. Below is an example of how to implement a basic intrusive list in C++.
#include
class IntrusiveNode {
public:
IntrusiveNode* next;
IntrusiveNode* prev;
IntrusiveNode() : next(nullptr), prev(nullptr) {}
};
class IntrusiveList {
private:
IntrusiveNode* head;
IntrusiveNode* tail;
public:
IntrusiveList() : head(nullptr), tail(nullptr) {}
void push_back(IntrusiveNode* node) {
if (!head) {
head = node;
tail = node;
node->next = node->prev = node; // point to itself
} else {
tail->next = node;
node->prev = tail;
node->next = head;
head->prev = node;
tail = node;
}
}
void remove(IntrusiveNode* node) {
if (node->prev) node->prev->next = node->next;
if (node->next) node->next->prev = node->prev;
if (node == head) head = node->next;
if (node == tail) tail = node->prev;
}
void display() {
IntrusiveNode* current = head;
if (!current) return;
do {
std::cout << current << " ";
current = current->next;
} while (current != head);
std::cout << std::endl;
}
};
int main() {
IntrusiveList list;
IntrusiveNode node1, node2, node3;
list.push_back(&node1);
list.push_back(&node2);
list.push_back(&node3);
list.display(); // Outputs the addresses of node1, node2, node3
list.remove(&node2);
list.display(); // Outputs the addresses of node1, node3
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?