![](/img/trans.png)
[英]Proper way to delete and free up memory of a vector (prevent different memory related errors) in c++
[英]What is the proper way to call the destructor to free up memory in a C++ operator?
我无法知道自己在做什么错。
Huge& Huge::operator *=(const Huge& h) {
Huge retHuge = *this * h;
string out1 = retHuge.toString(); // for debugging purposes
return *this = retHuge;
// return retHuge;
}
的
Huge retHuge = *this * h;
当我在字符串out1
验证时,效果很好。 如果返回retHuge并在调用例程中打印结果,则可以看到原来的内容保持不变。 如果执行*this = retHuge
并返回*this
, SEGSEGV
错误。
调用析构函数清理内存并在乘法后返回结果的正确方法是什么?
我要感谢大家的回答。 疯狂的埃迪(Crazy Eddie)使用了我所拥有的并扩展了它,这正是我想要做的。 我更改了资料来源以反映他的建议,然后出现SEGSEGV错误。
我的意思是说我的语法必须基本正确,但其余代码中却隐藏着一个错误。 这是有价值的信息,我需要回过头来,非常仔细地查看是否可以找到一些东西。 我不想懒惰,在正确完成作业之前先寻求帮助,所以我会先看起来不错。
我的经验主要是在Java上,它有一个不错的垃圾回收器来处理未引用的对象。 我将使用调试器,并验证是否调用了我的析构函数以释放内存。
尝试先执行* =运算符然后从中构建=运算符是一个很好的技巧。 显然,我做事的方向相反。 您的回答似乎仍然表明我所做的确实应该起作用。 由于它不起作用,我将回去看看是否能找到任何东西。 如果在完成作业后仍然找不到任何东西,我将继续询问。 同时,感谢您的所有帮助。
Huge& Huge::operator *=(const Huge& h) // class member function
{
// somehow multiply h's value into this' value
return *this;
}
Huge operator*(Huge lhs, const Huge& rhs) // free function; note lhs being copied
{
lhs *= rhs; // *= already implemented above
return lhs;
}
这里根本不涉及动态内存,因此您无需删除任何动态内存。
根据操作员重载的经验规则,复合赋值形式应为成员,因为它会更改其左手操作数(并且可能需要访问该类的私有部分)。 非分配版本应为自由成员函数,以便隐式转换可以同等地应用于两个操作数。
不要 delete this
; 之后, *this
将写入未分配的内存。
而是说*this = retHuge
(不delete this
),然后return *this
。
而是在operator =
处理释放。
这是一个完整的示例,其中包含一个虚假复杂的有效载荷int *
:
#include <iostream>
class A {
public:
A(int _val): val(new int(_val))
{ }
~A() {
delete this->val;
}
A &operator =(const A &r) {
// Pretend this->val is complex and we need to reallocate the
// entire thing.
delete this->val;
this->val = new int(*r.val);
return *this;
}
A operator *(const A &r) const {
return A(*this->val * *r.val);
}
A &operator *=(const A &r) {
return *this = *this * r;
}
int *val;
};
int main() {
A x(5), y(10);
x *= y;
std::cout << "x: " << *x.val << ", y: " << *y.val << std::endl;
return 0;
}
由于您似乎已经有了*运算符,并且在这一点上我将假定分配有效,因此这将是最佳实现:
Huge& Huge::operator *=(const Huge& h) {
Huge retHuge = *this * h;
return *this = retHuge;
}
operator=
表示您将右侧站点分配给this 。
因此,您应该更改this的内容,然后最后return *this;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.