Home > Enterprise >  C Using sizeof() to determine size of an Octree
C Using sizeof() to determine size of an Octree

Time:12-16

Let's say Octree() is a container with Elements of type double.

Can I use sizeof(Octree) to determine how much memory in bytes is taken up by my octree?

Sizeof() should change if I change the resolution/depth of my octree - which does not seem to be the case when I test it.

Is there a way I could determine the dynamically allocated memory size of my octree?

CodePudding user response:

No. sizeof returns the size of the object. Which is the size of the type of the object. Which remains constant through the entire program. sizeof does not return the amount of memory that member functions of the object have allocated dynamically, and it cannot be overloaded to do so.

Is there a way I could determine the dynamically allocated memory size of my octree?

Certainly. You can keep track of all dynamic memory that you allocate, and their sizes together to get the total. This won't include overhead consumed by the data structure used by the allocator itself. There's no standard way to measure that.

CodePudding user response:

As others said, sizeof only gives you the size (in bytes) of a single node (not including any storage pointed to by any member field of your node).

If you want to compute the actual size of a tree, you need something like this:

template <typename T>
std::size_t OctreeSize(const Octree<T> &tree_root_node) {
  std::size_t tree_size = 0;
  Visit(
   tree_root_node,
   [&tree_size] (const Octree<T> &node) {
     tree_size  = sizeof(node);
     // If you have any dynamically-allocated object
     // pointed to and owned by Octree<T>, add their size as well
  });
  return tree_size;
}

Where void Visit(const Octree<T> &, std::function<void(const Octree<T>&)> is a function that traverses each node of the tree and invokes the provided function.

  • Related