gpt4 book ai didi

c++ - 如何避免 C++ 类函数中的内存泄漏?

转载 作者:太空宇宙 更新时间:2023-11-04 14:36:00 25 4
gpt4 key购买 nike

<分区>

下面的代码一定可以运行。我的问题是我在类函数中分配了一些内存并返回了一个指向它的指针。但是在 main 函数中,我构建了一个新对象并将指针分配给它。但是如何释放返回的指针呢?我需要手动执行吗?

#include "stdio.h"

class Complex{

private:
float real;
float imaginary;

public:
Complex(float, float);
~Complex(void) {};
void set_real(float r);
void set_imaginary(float i);
float get_real();
float get_imaginary();
Complex* plus(Complex* another);
Complex* minus(Complex* another);
Complex* multiply(Complex* another);
};

Complex::Complex(float r, float i){
this->real = r;
this->imaginary = i;
}

void Complex::set_real(float r)
{this->real = r;}

void Complex::set_imaginary(float i)
{this->imaginary = i;}

float Complex::get_real()
{return real;}

float Complex::get_imaginary()
{return imaginary;}

Complex* Complex::plus(Complex* another){
Complex* result = new Complex(0,0);
result->set_real(this->real + another->real);
result->set_imaginary(this->imaginary + another->imaginary);
return result;
}

Complex* Complex::minus(Complex* another){
Complex* result = new Complex(0,0);
result->set_real(this->real - another->real);
result->set_imaginary(this->imaginary - another->imaginary);
return result;
}

Complex* Complex::multiply(Complex* another){
Complex* result = new Complex(0,0);
result->set_real((this->real * another->real) - (this->imaginary - another->imaginary));
result->set_imaginary((this->imaginary*another->real) + (this->real*another->imaginary));
return result;
}

int main(int argc, char* argv[]){
Complex* c = new Complex(3,4);
Complex* d = new Complex(6,9);
Complex* e = new Complex(0,0);

//will this line bring memory leak? Because all plus function already build a Complex object on leap. I don't know how to release it since I have to return it.
e = c->plus(d);

printf("result is %f + i%f", e->get_real(), e->get_imaginary());

delete c;
delete d;
delete e;
return 1;
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com