Finding out the largest size of several objects for placement new

主宰稳场 提交于 2019-12-10 19:06:19

问题


So I'm working on a small ARM embedded system that has pretty limited memory, and no MMU. I have several objects that I need to dynamically allocate for different functions that all inherit from the same superclass, but perform different functions and are likely different sizes. I don't have enough memory available to instantiate them all at startup and leave them in place.

So as an example, I might have objects defined sort of like:

class Waveform1 : public OutputStream
class Waveform2 : public OutputStream
class Waveform3 : public OutputStream

and the subclasses are going to have different sizes as some may have fewer methods and private variables than others, but likely none will be substantially larger than any of the others.

What I'd like to do is allocate a buffer to use with placement new at system startup that is large enough to contain the largest of the defined objects. Then I should be able to instantiate and destroy objects there without a problem, as it's always large enough to hold the largest of the objects required. I'd like this to be taken care of automatically, as new objects may be added to the list as system design progresses.

Is there a canonical way to accomplish this so it might sort of seem like I know what I'm doing?


回答1:


What I've done in the past is use a union of a char array and all of the types I need to store in it. The benefit is that the buffer will be aligned properly.

Something like:

class MyClass {
    public:
        union {
            char buffer[1];
            ClassA a;
            ClassB b;
        };
    MyClass() {}
    ~MyClass() {}
};

Note that you can just leave out the char buffer[1] and placement new right onto the class member of the union, like new (&a) ClassA. Also note that if ClassA or ClassB are anything except PODs then this only works in C++11.

Now, it turns out that what I actually did do is different from what I remember doing. Probably because I had to support C++03. In my actual code I did this:

char DECLARE_ALIGN(8) buffer[ sizeof(int*) * 8 ];

DECLARE_ALIGN is either:

#  define DECLARE_ALIGN(x)  __attribute__((aligned(x)))

Or

# define DECLARE_ALIGN(x) __declspec( align(x) )

And then later in the code, in the function that was actually allocating the object and after I had passed buffer as a pointer, and sizeof(buffer) as buffer_len:

assert( buffer==0 || buffer_len >= sizeof(BTreeNodeWriter_X<X>) );
assert( buffer==0 || buffer_len >= sizeof(BTreePackedNodeWriter_X<X>) );


来源:https://stackoverflow.com/questions/35371369/finding-out-the-largest-size-of-several-objects-for-placement-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!