C++ 类析构函数中的错误
我刚开始我的容器类,我已经有问题了:C++ 类析构函数中的错误,c++,class,pointers,memory-leaks,destructor,C++,Class,Pointers,Memory Leaks,Destructor,我刚开始我的容器类,我已经有问题了: class Container { private: string* BasePointer; // The starting pointer. unsigned int Capacity; // The number of values the container can hold. public: Container() // Default constructor. { Capaci
class Container
{
private:
string* BasePointer; // The starting pointer.
unsigned int Capacity; // The number of values the container can hold.
public:
Container() // Default constructor.
{
Capacity = 1;
BasePointer = new string[Capacity];
}
~Container() // Destructor.
{
delete BasePointer; // Delete the container to prevent memory leaking.
}
};
我得到错误
容器类(26467)malloc:**object 0x100100088的错误:未分配要释放的指针。我做错了什么?XXX ptr=new XXX[size]
应该与数组版本delete[]ptr
匹配,而不仅仅是常规删除
在C++中阅读,如杰姆斯提醒我们的那样,按照这种情况进行。
必须使用Dele[] /P>
delete[] BasePointer;
Hi如果创建数组,则必须使用delete[]BasePointer 要比其他类型更明确-当您new
编辑数组类型时,需要使用delete[]
删除指针
<>这不仅发生在使用<代码>新的t[Stsie] < /C>时,请考虑以下示例:
typedef int T[42];
int* x = new T;
delete[] x; // needs delete[] though you used new without []
一般来说,如果你的对象“拥有”一个通过指针保存的对象,你应该考虑使用一个智能指针(比如Booo::SimeDePixLoad)。这样,您就不必担心解构,当抛出异常时会发生什么,实现赋值运算和复制构造函数…其他人提到您将new[]
与delete
不匹配,您必须将delete
更改为delete[]
来修复它。然而,这只是你的第一个问题
您还需要实现(或至少声明为私有)复制构造函数和复制赋值运算符。否则,请思考当您这样做时会发生什么:
{
Container c1;
Container c2(c1);
} // c2.~Container(); // frees the memory pointed to by 'BasePointer'
// c1.~Container(); // also frees the memory pointed to by 'BasePointer'.
由于c1
和c2
的BasePointer
成员都指向同一个数组,因此它会被释放两次
有一些更容易使用的替代方案:
- 考虑在任何可能使用动态分配数组的地方使用
std::vector
。由于您的类被称为容器
,因此我假设您正在尝试实现一个拥有资源的容器,所以可能不想使用它
- 考虑使用
boost::scoped_ptr
或std::unique_ptr
(如果编译器支持)来管理指针的所有权。这两种方法都抑制隐式声明的复制构造函数的生成,如果您实际尝试使用它们,则强制您实现自己的复制构造函数
即使您正在实现一个容器
,您仍然应该利用更多的基本容器来完成繁重的工作(或者,至少重新实现这些基本容器,以便将繁重的工作整合到一组小的实用程序中)
最后,从风格上讲,容器不需要使用malloc
。标准库提供了std::allocator
,可用于为对象分配空间和构造对象。正是我所想的谢谢。[]
是否有语法上的原因?它是否可以包含可选参数或其他内容?不,不能提供参数。原因是——好吧,它所做的与delete所做的不同,因此它需要一个不同的名称;)它被称为析构函数,就像在destruction中一样。不是解构器。:)