我正在为嵌入式平台编写代码,因此我不能使用普通的新操作符。
现在,我想将任意对象添加到列表中,如下所示。
tp.add(DerivedA("David"));
tp.add(DerivedB("Max"));
tp.add(DerivedC("Thomas"));由于代码复制的原因,我不想写这样的东西:
DerivedA david("David");
tp.add(david);
...一个解决方案,但不是很漂亮的风格是这样的:
tp.add(new (myalloc(sizeof(DerivedB))) DerivedB("John"));
// using placement-new works现在,我尝试添加一个通过指针传递的临时对象:
tp.add(&DerivedA("David")); 理论上这是可行的,但编译器抱怨(有充分理由)将指针传递到临时对象(-fpermissive)。
有没有一种干净的方法来做我想做的?
下面是一个完整的例子:
#include <iostream>
using namespace std;
class Base // base class
{
public:
Base();
int size;
char name[100];
};
class Derived:public Base
{
public:
Derived(char* name);
};
class ThirdParty
{
public:
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
tp.addTemp(&Derived("Max"));
tp.addTemp(&Derived("Thomas"));
return 0;
}
Base::Base()
{
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;
}发布于 2016-11-12 11:50:14
我现在最喜欢的解决方案是以下宏:
#define m(x) new (myalloc(sizeof(x))) x现在,我可以用以下代码添加一个新对象:
tp.add(m(Derived("Isabella")));发布于 2016-11-09 09:28:00
如果使用C++11,可以编写一个转发函数来完成以下工作:
template <typename T, typename... Args>
T* make (Args&&... args) {
return new (myalloc(sizeof(T))) T { std::forward<Args>(args)... };
}然后将一个对象添加到列表中,如下所示:
tp.add(make<Derived>("John"));发布于 2016-11-12 11:58:55
你就不能重写新的使用myalloc吗?如果你不想在全球范围内这样做,你当然可以为基地做
https://stackoverflow.com/questions/40503012
复制相似问题