nixd
Loading...
Searching...
No Matches
PtrPool.h
Go to the documentation of this file.
1/// \file
2/// \brief Pointer pool, for RAII memory management.
3
4// TODO: This file is trivial and shared among many libraries, maybe should move
5// this in a standalone public header.
6
7#pragma once
8
9#include <memory>
10#include <vector>
11
12namespace nixt {
13
14/// \brief A simple pointer pool, a vector of `unique_ptr`s.
15///
16/// It is used for "owning" nodes. Other classes can use weak/raw pointers to
17/// the nodes, to avoid cyclic references.
18///
19/// Also in nix AST, the nodes are not owned by it's parent because in bison
20/// algorithm nodes should be copyable while performing shift-reduce. So in our
21/// implementation nodes are owned in this structure.
22template <class T> struct PtrPool {
23 std::vector<std::unique_ptr<T>> Nodes;
24
25 /// \brief Takes ownership of a node, add it to the pool.
26 template <class U> U *add(std::unique_ptr<U> Node) {
27 Nodes.push_back(std::move(Node));
28 return dynamic_cast<U *>(Nodes.back().get());
29 }
30
31 /// \brief Takes ownership from a raw pointer.
32 ///
33 /// \note This should only be used when it is allocated by "malloc", and not
34 /// owned by other objects (otherwise it will cause double free).
35 template <class U> U *record(U *Node) {
36 Nodes.emplace_back(std::unique_ptr<U>(Node));
37 return Node;
38 }
39};
40
41} // namespace nixt
Access EvalCache in nix::EvalState.
Definition ArrayRef.h:7
A simple pointer pool, a vector of unique_ptrs.
Definition PtrPool.h:22
std::vector< std::unique_ptr< T > > Nodes
Definition PtrPool.h:23
U * add(std::unique_ptr< U > Node)
Takes ownership of a node, add it to the pool.
Definition PtrPool.h:26
U * record(U *Node)
Takes ownership from a raw pointer.
Definition PtrPool.h:35