What does it mean for a data structure to be “intrusive”?

后端 未结 2 1731
时光取名叫无心
时光取名叫无心 2020-12-12 10:35

I\'ve seen the term intrusive used to describe data structures like lists and stacks, but what does it mean?

Can you give a code example of an intrusive dat

2条回答
  •  被撕碎了的回忆
    2020-12-12 10:56

    In a intrusive container the data itself is responsible for storing the necessary information for the container. That means that on the one side the data type needs to be specialized depending on how it will be stored, on the other side it means that the data "knows" how it is stored and thus can be optimized slightly better.

    Non-intrusive:

    template
    class LinkedList
    {
      struct ListItem
      {
        T Value;
        ListItem* Prev;
        ListItem* Next;
      };
    
      ListItem* FirstItem;
      ListItem* LastItem;
    
      [...]
      ListItem* append(T&& val)
      {
        LastItem = LastItem.Next = new ListItem{val, LastItem, nullptr};
      };
    };
    
    LinkedList IntList;
    

    Intrusive:

    template
    class LinkedList
    {
      T* FirstItem;
      T* LastItem;
    
      [...]
      T* append(T&& val)
      {
        T* newValue = new T(val);
        newValue.Next = nullptr;
        newValue.Prev = LastItem;
        LastItem.Next = newValue;
        LastItem = newValue;
      };
    };
    
    struct IntListItem
    {
      int Value;
      IntListItem* Prev;
      IntListItem* Next;
    };
    
    LinkedList IntList;
    

    Personally I prefer intrusive design for it's transparency.

提交回复
热议问题