【问题标题】:Dynamic memory allocation in constructor构造函数中的动态内存分配
【发布时间】:2017-08-17 04:41:35
【问题描述】:

我正在学习动态内存分配。我有以下类,其中“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 

【问题讨论】:

标签: c++ constructor destructor copy-constructor dynamic-memory-allocation


【解决方案1】:

对于初学者,您的默认构造函数使用相同类型的局部变量覆盖成员变量“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];
   }
}

【讨论】:

  • 将数组大小硬编码为 12 是一个非常糟糕的主意,顺便说一句,至少在某处添加一个 #define 或 static const int。
  • “添加 #define 或静态 const int”到底是什么意思?我对这种东西的经验很少。 ;)
  • 如果你的数组总是 12 的大小,那么在你的类中添加一个 static const int ARRAY_SIZE = 12; 然后当你想放 12 时,放 ARRAY_SIZE 代替。如果这个数组是可变长度的,那么这是不需要的。
  • “正在覆盖成员变量” 在传统术语中:“隐藏成员变量”
  • 根据您的输入,我现在已将 12 更改为 'len' 并将 'int len' 添加到 'private'。但是当我编译时,程序会不断调用构造函数并且不会停止。我该如何解决这个问题?
【解决方案2】:

查看此代码:

#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;
}

【讨论】:

  • 此实例中的 array 和 array2 都将指向同一个缓冲区,因为您的复制构造函数将复制指针,而不是新的离散数组。这将在破坏时崩溃。
  • 我更改了代码以进行深层复制。谢谢提及!
  • 你肯定用原始代码在同一块内存上调用了两次删除,这是错误的。
猜你喜欢
  • 1970-01-01
  • 2016-07-29
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 2021-11-29
相关资源
最近更新 更多