我的应用程序使用了大量的 Panda
对象。每个 Panda
都有一个 Bamboo
对象列表。一旦 Panda
被初始化(没有添加或删除 Bamboo
对象),这个列表就不会改变。目前,我的类实现如下:
class Panda
{
int a;
int b;
int _bambooCount;
Bamboo* _bamboo;
Panda (int count, Bamboo* bamboo)
{
_bambooCount = count;
_bamboo = new Bamboo[count];
// ... copy bamboo into the array ...
}
}
为了减轻分配 Bamboo
对象数组的开销,我可以按如下方式实现这个类——基本上,不是通过常规构造函数创建对象,构造方法分配一个内存块同时保存 Panda
对象及其 Bamboo
数组:
class Panda
{
int a;
int b;
Panda ()
{
// ... other initializations here ...
}
static Panda *createPanda (int count, Bamboo* bamboo)
{
byte* p = new byte[sizeof(Panda) +
sizeof(Bamboo) * count];
new (p) Panda ();
Bamboo* bamboo = (Bamboo*)
p + sizeof(Panda);
// ... copy bamboo objects into the memory
// behind the object...
return (Panda*)p;
}
}
除了增加维护工作量之外,您能预见第二种设计的任何问题吗?这是一个可以接受的设计模式,还是只是一个过早的优化,以后可能会回来咬我?
最佳答案
C++ 为您提供了另一种选择。您应该考虑使用 std::vector。
class Panda
{
int a;
int b;
std::vector<Bamboo> bamboo;
// if you do not want to store by value:
//std::vector< shared_ptr<Bamboo> > bamboo;
Panda (int count, Bamboo* bamb) : bamboo( bamb, bamb+count ) {}
}
如果您想将 Pandas 和竹子存储在连续内存中,您可以使用 this article 中的解决方案.主要思想是重载operator new
和operator delete
。
关于c++ - 变长对象 : Ever a good idea?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1390073/