Sah*_*pre 5 c++ oop malloc constructor class
我正在实现二进制堆类.堆实现为动态分配的数组.堆类具有成员容量,大小和指向数组的指针,如下所示:
class Heap
{
private:
Heap* H;
int capacity; //Size of the array.
int size; //Number of elements currently in the array
ElementType* Elements; //Pointer to the array of size (capacity+1)
//I've omitted the rest of the class.
};
Run Code Online (Sandbox Code Playgroud)
我的建筑看起来像这样:
Heap::Heap (int maxElements)
{
H = ( Heap* ) malloc ( sizeof ( Heap ) );
H -> Elements = ( ElementType* ) malloc ( ( maxElements+1 )*sizeof ( ElementType ) );
H -> Elements[0] = DUMMY_VALUE; //Dummy value
H -> capacity = maxElements;
H -> size = 0;
}
Run Code Online (Sandbox Code Playgroud)
由于我在mallocing两次并在构造函数中解除引用两个指针,我应该检查它是否成功.但如果它失败了我该怎么办?构造函数本身不能返回任何内容以指示它失败.完全避免构造函数中的mallocs是一种很好的编程习惯吗?
HC4*_*ica 14
首先,你就不会需要一个Heap*
成员变量的内部Heap
对象,你当然不应该为它在分配内存Heap
构造-这只是自找麻烦.您也不应该访问您的成员变量H->Elements
,而是简单地访问Elements
.
您需要分配的唯一内容是Elements
数组.
关于处理分配失败,构造函数应该通过异常指示失败.甚至有一种标准的异常类型,std::bad_alloc
通常用于指示分配内存失败.
例如:
#include <stdexcept> // for std::bad_alloc
...
Heap::Heap (int maxElements)
{
Elements = ( ElementType* ) malloc ( ( maxElements+1 )*sizeof ( ElementType ) );
if (Elements == NULL)
throw std::bad_alloc("Failed to allocate memory");
...
}
Run Code Online (Sandbox Code Playgroud)
更好的是,使用new
而不是malloc
分配内存.如果无法分配内存,new
将自动抛出类型异常std::bad_alloc
.
例:
Heap::Heap (int maxElements)
{
Elements = new ElementType[maxElements + 1]; // throws std::bad_alloc on failure
...
}
Run Code Online (Sandbox Code Playgroud)
注意:如果您使用new
分配对象,则必须使用delete
它来释放它而不是free
.(更正:在上面的例子中,你使用的是new的数组形式new[]
,所以你应该调用delete的数组形式delete[]
).
最后,你有没有看到如何ElementType
声明,但如果它是具有非默认构造函数/析构型(或者如果它,这意味着它有可能成为这种类型的模板参数),你必须使用new
,而不是malloc
当分配它因为malloc
不会调用构造函数(并且free
不会调用析构函数).在一般情况下,这是很好的做法,只是一直用new
和delete
C++中,而不是malloc
和free
.
你应该学习一些基本的C++"道路规则",第一个是:
使用标准模板库!
class Heap {
private:
std::vector<ElementType> elements;
}
Run Code Online (Sandbox Code Playgroud)
还有你的构造函数?你不需要一个.
通常,在C++中使用malloc()
或使用free()
C++都是一种"代码味道".这是一种肯定的方式,可以最终导致错误构造的对象,缓冲区溢出和内存泄漏.使用new
和delete
,最好使用智能指针.
或者,更好.尽可能静态地构建对象.