Reputation: 584
I'm wondering if there's a standard C++ class which is the equivalent of a tailq. I could use the c implementation of a tailq, but it uses lots of macros and is somewhat ugly.
Basically, I have a class, which each instance has to be part of multiple lists. To avoid extra malloc's/memory dereferences, I'd like to store the next
and prev
pointers within the class itself. Does C++ have a clever way of doing this, or am I better off just using <sys/queue.h>
?
Upvotes: 1
Views: 396
Reputation: 1072
There's no problem storing pointers of the class inside itself. The following code compiles just fine:
class A
{
A* next;
A* prev;
};
This will allow you to have pointers for multiple lists inside the object:
class A
{
std::vector<A*> next;
std::vector<A*> prev;
};
Upvotes: 0
Reputation: 75853
In C++
I would have containers of shared_ptr
. It doesn't matter, it can be std::list
or std::vector
or any container. Because with shared_ptr
you have each element allocated separately, I don't see any good reason to use std::list
so I would go for std::vector<std::shared_ptr<X>>
Example:
#include <memory>
#include <vector>
#include <iostream>
struct X { int a = 0; X() = default; X(int p) { a = p; } };
auto operator<<(std::ostream& os, X x) -> std::ostream&
{
os << x.a;
return os;
}
int main()
{
auto x1 = std::make_shared<X>(24);
auto x2 = std::make_shared<X>(11);
auto x3 = std::make_shared<X>(1024);
auto x4 = std::make_shared<X>(5);
std::vector<std::shared_ptr<X>> v1 = {x1, x2, x3, x4};
std::vector<std::shared_ptr<X>> v2 = {x3, x1, x4};
// modify an object and observe the change in both lists
x1->a = -24;
for (const auto& e : v1)
std::cout << *e << ' ';
std::cout << '\n';
for (const auto& e : v2)
std::cout << *e << ' ';
std::cout << '\n';
}
the output is:
-24 11 1024 5
1024 -24 5
Upvotes: 1