动态分配数组时设置Ctor参数

Setting Ctor params when dynamically allocating an array

本文关键字:Ctor 参数 设置 数组 动态分配      更新时间:2023-10-16

我正在尝试动态分配对象数组。我的每个对象在构造函数中有一个必须初始化的参数。我更喜欢在构造时初始化它们,因为我认为这样可以节省时间。如何在分配时使用需要参数的构造函数初始化动态分配对象的数组?

class Thingy{
private:
    int* a;
public:
    Thingy(int size);
};
class ThingyLayer{
private:
    Thingy* m_things;
public:
    ThingyLayer(int n){
        m_things = new Thingy[n]; //!< How do I pass a param here to the ctor of Thingy
    }
};

在这种情况下我宁愿不使用std::vector,因为有一天我可能想在不支持STL的嵌入式系统上运行它,比如Atmel AVR芯片。所以我正在寻找如何做到这一点与指针。

我已经尝试过了,m_things = new Thingy[n](val),但这不起作用,因为它会引发编译器警告。我还查看了动态分配对象数组,但这并没有回答我的问题。

c++的方法是std::vector (和我不相信你,你真的有一个很好的理由使用指针代替好吧,你命名了一个原因,我不能真正判断如果它是一个很好的,因为我没有嵌入式系统的知识):

class ThingyLayer{
private:
    std::vector<Thingy> m_things;
public:
    ThingyLayer(int n) : m_things(n,val){}
};

这也使您避免了手动newdelete的痛苦,这不是一件有趣的事情。

std::vector还附带了一大堆其他整洁的功能,如果您不熟悉它,请查看我链接的手册页。

您可以使用:

ThingyLayer(int n){
    char* temp = new char[sizeof(Thingy)*n];
    for (int i = 0; i < n; ++i )
    {
        // Use placement new to construct Thingy objects.
        new (temp+i*sizeof(Thingy)) Thingy(10); // Assuming 10 here.
    }
    m_things = reinterpret_cast<Thingy*>(temp);
}

我有点犹豫,因为Thingy的对齐要求是char不同的。我不确定这会如何影响代码的行为。

如果你遵循这条路径,ThingyLayer的析构函数也必须精心制作。

class ThingyLayer
{
   private:
      int m_n;
      Thingy* m_things;
   public:
      ThingyLayer(int n) : m_n(n) {
         char* temp = new char[sizeof(Thingy)*n];
         for (int i = 0; i < n; ++i )
         {
            // Use placement new to construct Thingy objects.
            new (temp+i*sizeof(Thingy)) Thingy(10); // Assuming 10 here.
         }
         m_things = reinterpret_cast<Thingy*>(temp);
      }
      ~ThingyLayer()
      {
         for (int i = 0; i < m_n; ++i )
         {
            // Call the destructor of Thingy explicitly.
            m_things[i].~Thingy();
         }
         // Now deallocate the memory using a char*.
         char* temp = reinterpret_cast<char*>(m_things);
         delete [] temp;
      }
      // Make sure to implement copy constructor and copy assignment 
      // operator properly. If you use the default copy constructor and
      // copy assignment operator, the program will exhibit undefined
      // behavior.
      ThingyLayer(ThingyLayer const& copy) { ... }
      ThingyLayer& operator=(ThingyLayer const& rhs) { ... }
};

深入阅读:什么是三法则?