构造函数中的动态内存分配

Dynamic memory allocation in constructor

本文关键字:内存 分配 动态 构造函数      更新时间:2023-10-16

我正在学习动态内存分配。我有以下类,其中"类 A"应该在构造函数中拥有一个动态分配的数组。还应修改复制构造函数和析构函数。这就是我到目前为止所拥有的...

#include <iostream>
#ifndef A_HH
#define A_HH
#include "B.hh"
class A {
public:
  A() {  B *array = new B[12];}
  A(const A&) { /* Do not know what to put here..*/ }
  ~A() { delete[] array;}
private:
   //B array[12] ; <- This is the array that I have to modify so it becomes dynamic. 
   B *array;
} ;
#endif 

对于初学者,您的默认构造函数会用相同类型的局部变量覆盖成员变量"array",因此您希望默认构造函数如下所示:

A() { array = new B[12]; }
然后,复制

构造函数可能需要将数组深层复制过来,但是对于一个简单的数组,您无法在运行时分辨数组大小。您需要移动到更智能的容器(例如 stl::vector(或存储大小,但朴素的复制构造函数如下所示:

A(const A& other)
{
   array = new B[12];
   for(int i=0;i<12;i++)
   {
       array[i] = other.array[i];
   }
}

查看此代码:

#include <iostream>

using namespace std;
class MyArray{
public:
    int* array;
    int length;
    MyArray(int length){ // constructor which takes length of array as argument
        this->length = length;
        this->array = new int[this->length];
        for(int i=0; i<this->length; i++){
            this->array[i] = i;
        }
    }
    MyArray(const MyArray &obj){
        this->length = obj.length;
        this->array = new int[this->length];
        for(int i=0; i<this->length; i++)
        {
            this->array[i] = obj.array[i];
        }
    }
    ~MyArray(){ // destructor
        delete[] this->array;
    }

    void print(){ // test method for printing the array
    for(int i=0; i<this->length; i++){
            cout << this->array[i] << endl;
        }
        cout << endl;
    }
private:
protected:
};
int main()
{
    MyArray *array = new MyArray(10);
    MyArray *array2 = new MyArray(*array); // call copy constructor
    array->print();
    array2->print();
    delete array;
    delete array2;
}