簡體   English   中英

C ++在類指針數組上使用delete []

[英]C++ Using delete[] on an Array of Class Pointers

T** class_array
/* snip: malloc/creating classes */
delete[] class_array

delete []是否可以正確調用free class_array(類指針數組)和必需的析構函數?

不,不會。

以下可能是一個示例示例,與我想嘗試的操作類似。 不需要顯式刪除,它由arr_of_arr的析構函數執行。

#include <iostream>
#include <memory>

using std::unique_ptr;
using std::cout;

class A
  {
  public:
    A() { my_cnt = cnt++; cout << "cons " << my_cnt << '\n'; }
    ~A() { cout << "kill " << my_cnt << '\n'; }

  private:
    unsigned my_cnt;
    static unsigned cnt;
  };

unsigned A::cnt;

int main()
  {
    unique_ptr<unique_ptr<A []> []> arr_of_arr(new unique_ptr<A []>[3]);

    arr_of_arr[0] = unique_ptr<A []>(new A[1]);
    arr_of_arr[1] = unique_ptr<A []>(new A[2]);
    arr_of_arr[2] = unique_ptr<A []>(new A[3]);

    return(0);
  }

暫無
暫無

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

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