1

So, I'm a bit confused. I need to be able to create many (up to a billion) small (<8 elements) fixed-sized arrays at runtime. I was using std::vector, but the memory overhead was too high (24 bytes per array).

I decided to implement my own array, templated on the contained type (T1) and the type storing the static size of the array (T2).

The class is called lw_vector. If I call:

sizeof(lw_vector<int, unsigned char>) 

I get 16. However, as I calculate it, the size should be sizeof(int*)+sizeof(unsigned char)=9 on a 64-bit system. What am I doing wrong here? Is it possible to create an object that only requires 9 bytes of memory?

Here's the implementation of lw_vector:

template<class T1, class T2>
class lw_vector
{
private:
public:
    T2 N;
    T1 * content;

    lw_vector() : N(0)
    {}

    lw_vector(T2 Nt) : N(Nt)
    {
        content = new T1[N];
    }

    ~lw_vector()
    {
        delete[] content;
    }

    lw_vector& operator=(lw_vector temp)
    {
        std::swap(N, temp.N);
        std::swap(content, temp.content);
        return *this;
    }

    lw_vector(const lw_vector& other)
        : N(other.N),
        content(new T1[other.N])
    {
        std::copy(other.content, other.content + N, content);
    }

    inline T1& operator[](T2 ind) const
    {
        return content[ind];
    }
};

Thank you for your time!

John

David G
  • 94,763
  • 41
  • 167
  • 253
  • You fail to take memory alignment into consideration. Also, I'd suggest really profiling std::vector for your needs before reinventing the wheel. – StoryTeller - Unslander Monica Jun 08 '14 at 22:33
  • `I need to be able to create many (up to a billion) small (<8 elements) fixed-sized arrays at runtime` Maybe you should think about this aspect of your program first. Why do you need up to a billion individual arrays? – PaulMcKenzie Jun 08 '14 at 22:37
  • Thanks for the comment. It's because I'm creating a mesh generation program which can have up to a billion elements. The elements need node id's, etc. And each type of element will have a different number of node ID's. That's why I was favoring vectors/arrays. However, it would be possible to fix with inheritance/raw compile-time arrays I suppose. – user3335011 Jun 08 '14 at 22:40
  • 1
    @user3335011 - Maybe you should look into this? http://stackoverflow.com/questions/20486587/flyweight-pattern-in-c http://en.wikipedia.org/wiki/Flyweight_pattern – PaulMcKenzie Jun 08 '14 at 23:13

0 Answers0