指向固定大小数组的指针的析构函数
假设我有一个带有两个私有变量的 C++ 类。固定大小的数组 data
和指向该数组的指针 pnt
。
class MyClass
{
private:
double *pnt;
double data[2];
public:
myClass();
virtual ~MyClass();
double* getPnt() const;
void setPnt(double* input);
};
MyClass::MyClass()
{
double * input;
data[0] = 1;
data[1] = 2;
input= data;
setPnt(input);
}
MyClass::~MyClass()
{
delete this->pnt; // This throws a runtime error
}
void MyClass::setPnt(double * input)
{
pnt = input;
}
double * MyClass::getPnt() const;
{
return pnt;
}
int main()
{
MyClass spam; // Construct object
delete spam; // Error C2440: 'delete' cannot convert from 'MyClass' to 'void*'
}
这段代码有两个问题。首先,如果我尝试对对象调用删除,我会得到:
错误 C2440:“删除”无法从“MyClass”转换为“void*”
其次,如果我注释掉删除语句,我会收到一个实时错误,指出调试断言失败!这是:
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
我的问题是:对于带有指向私有固定大小数组的指针的类,如何正确释放内存,编写/调用析构函数?
PS我不能使用矢量或类似的漂亮容器(因此是这个问题)。
Suppose I have a C++ class with two private variables. A fixed size array, data
, and a pointer to that array, pnt
.
class MyClass
{
private:
double *pnt;
double data[2];
public:
myClass();
virtual ~MyClass();
double* getPnt() const;
void setPnt(double* input);
};
MyClass::MyClass()
{
double * input;
data[0] = 1;
data[1] = 2;
input= data;
setPnt(input);
}
MyClass::~MyClass()
{
delete this->pnt; // This throws a runtime error
}
void MyClass::setPnt(double * input)
{
pnt = input;
}
double * MyClass::getPnt() const;
{
return pnt;
}
int main()
{
MyClass spam; // Construct object
delete spam; // Error C2440: 'delete' cannot convert from 'MyClass' to 'void*'
}
There are two problems with this code. First if I try to call delete on the object, I get:
Error C2440: 'delete' cannot convert from 'MyClass' to 'void*'
Secondly, if I comment out the delete statement, I get a realtime error stating a debug assertion failed! and this:
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
My question is then: For a class with a pointer to a private fixed size array, how do I properly free memory, write/call the destructor?
P.S I can't use vector
or nice containers like that (hence this question).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我没有看到静态数组。我看到一个固定大小的数组。此外,
data
的内存也作为对象的一部分进行分配。您不得显式删除类的成员:删除运算符将处理动态分配的实例IFF。
与
I see no static array. I see a fixed-size array. Also memory for
data
is allocated as part of the object.You must not explicitely delete a member of the class: the delete operator will take care of that IFF the instance was dynamically allocated.
vs.
data
是一个子对象,当MyClass
实例消失时它将被释放。编译器会将任何必要的代码插入到 MyClass 析构函数中,以便在释放内存之前调用所有子对象的析构函数。data
is a subobject, it will be deallocated when theMyClass
instance goes away. The compiler will insert any necessary code into theMyClass
destructor to call destructors for all subobjects before the memory is freed.