Karl Zeilhofer Karl Zeilhofer - 1 year ago 88
C++ Question

C++, adding temporary objects to a list, without dynamic memory allocation

I'm writing code for an embedded platform, therefore I cannot use the normal new operator.

Now I want to add arbitrary objects to a list, just like this.


For the reason of code duplication I don't want to write something like this:

DerivedA david("David");

A solution, but not very pretty style would be this:

tp.add(new (myalloc(sizeof(DerivedB))) DerivedB("John"));
// using placement-new works

Now I tried to add a temporary object, passed by pointer:


Theoretically this could work, but the compiler complains (with good reason) about passing a pointer to a temporary object (-fpermissive).

Is there a clean way of doing what I want to?

Here is a full example:

#include <iostream>

using namespace std;

class Base // base class
int size;
char name[100];

class Derived:public Base
Derived(char* name);

class ThirdParty
void add(Base* obj);
void addTemp(Base* tempObj);
Base* list[10];
int index;

void* myalloc(int size){
void* p;
// ...
// allocate memory in a static memory pool
// ...
return p;

void memcpy(void* to, void* from, int size){


int main()
ThirdParty tp;

// The ugly style:
tp.add(new (myalloc(sizeof(Derived))) Derived("John")); // using placement-new works

// The beauty style (compiler complains here):
tp.addTemp(&Derived("David")); // create temporary object here, which is copied and added to the list

return 0;

size = sizeof(Base);

Derived::Derived(char *name)
size = sizeof(Derived); // make size of this object available for a base-pointer

void ThirdParty::add(Base *obj)
list[index++] = obj;

void ThirdParty::addTemp(Base* tempObj)
Base* newObj = (Base*) myalloc(tempObj->size); // let third party allocate memory
memcpy(newObj, tempObj, tempObj->size); // copy the temporary object
list[index++] = newObj;

Answer Source

My preferred solution now is the following macro:

#define m(x) new (myalloc(sizeof(x))) x

now I can add a new object with this code:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download