c++ - 变长对象 : Ever a good idea?

标签 c++ design-patterns data-structures class-design

我的应用程序使用了大量的 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 newoperator delete

关于c++ - 变长对象 : Ever a good idea?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1390073/

相关文章:

haskell - 二维 zipper

c++ - 从qt中的文件中删除一行?

c++ - 在 C++ 中扩展 C 结构

c++ - 在 boost::siginfo 处理程序中从 siginfo 获取 sig_int 值

c# - C# 中 ValidationError 类的合理模式

具有太多属性的java编辑对象

c++ - 在 Windows 和 Linux 下处理不同源目录和对象目录的 Makefile

Javascript 模块化设计模式 - : self-invoking function, 或对象文字方法哪个更好?

algorithm - 在内存中维护前 100 个列表

Python - 定向边列表到字典的字典