我的应用程序使用了大量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;
}
}除了增加的维护工作之外,您还能预见到第二种设计的任何问题吗?这是一种可接受的设计模式,还是仅仅是一种过早的优化,以后可能会回来咬我?
发布于 2009-09-07 16:31:38
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 ) {}
}如果你想在连续内存中存储熊猫和竹子,你可以使用this article的解决方案。其主要思想是重载operator new和operator delete。
发布于 2009-09-07 16:58:00
我们如何让人们相信,编程的简单性和清晰性--简而言之:数学家所说的“优雅”--不是可有可无的奢侈品,而是决定成败的关键问题?
-- Edsger W. Dijkstra
发布于 2009-09-07 16:30:42
如果有人按价值拿了一只熊猫,你会被咬的。
//compiler allocates 16-bytes on the stack for this local variable
Panda panda = *createPanda(15, bamboo);如果你只通过指针而不是通过值来引用事物,并且你要注意复制构造函数和赋值操作符,那么这可能是可以接受的(但很可能是一个不成熟且可怕的优化)。
https://stackoverflow.com/questions/1390073
复制相似问题