簡體   English   中英

多維動態數組中的C ++對象構造

[英]C++ object construction in a multidimensional dynamic array

我正在嘗試創建一個nxn對象數組,但我不知道在哪里調用它們的構造函數。 這是我的代碼:

class obj {
  private: int x;
  public:  obj( int _x ) { x = _x; }
};

int main( int argc, const char* argv[] ) {

  int n = 3; //matrix size    

  obj** matrix = new obj*[n];
  for( int i = 0; i < n; i++ )
    matrix[i] = new obj[n];

  return 0;
}

如果只需要默認構造函數調用,則代碼已經調用它。

對於非默認構造函數,添加嵌套循環,如下所示:

for( int i = 0; i < n; i++ ) {
    matrix[i] = new obj[n];
    for (int j = 0 ; j != n ; j++) {
        matrix[i][j] = obj(arg1, arg2, arg3); // Non-default constructor
    }
}

更好的方法是使用obj std::vector of obj如果不需要多態行為,或者如果需要多態行為則使用obj的智能指針。

如果你真的想要使用低級內存管理,那么你不能 - new的數組形式不允許你將參數傳遞給對象的構造函數。 你可以做的最好的事情是讓它們默認構造(如果需要的話,在你的類中添加一個構造函數),然后循環並重新分配它們。 這很乏味且容易出錯。

我建議使用更高級別的課程; 對於動態數組,使用向量:

std::vector<std::vector<obj>> matrix(n);
for (auto & row : matrix) {
    row.reserve(n);
    for (size_t i = 0; i < n; ++n) {
        row.emplace_back(/* constructor argument(s) here */);
    }
}

作為獎勵, RAII意味着您不需要自己刪除所有分配,並且如果其中任何一個失敗,它將不會泄漏內存。

dasblinkenlight已經給出了相當不錯的答案,但是,還有第二種方法可以做到更有效率。 因為,如果你這樣做(代碼取自他的回答)

matrix[i] = new obj[n];
for (int j = 0 ; j != n ; j++) {
    matrix[i][j] = obj(arg1, arg2, arg3); // Non-default constructor
}

以下將發生:

  1. 分配n對象的內存。

  2. 所有n對象都是默認構造的。

  3. 對於每個對象,在堆棧​​上自定義構造新對象。

  4. 堆棧上的此對象將復制到已分配的對象中。

  5. 堆棧上的對象被破壞。

顯然遠遠超過必要的(雖然完全正確)。

您可以使用展示位置新語法來解決此問題:

matrix[i] = (obj*)new char[n*sizeof obj];    //Allocate only memory, do not construct!
for (int j = 0 ; j != n ; j++) {
    new (&matrix[i][j]) obj(arg1, arg2, arg3); // Non-default constructor called directly on the object in the matrix.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM