[cdl-studenti] [OOP] Eliberare automata de memorie.
Dan-George Filimon
dangeorge.filimon at gmail.com
Sat Mar 6 16:34:04 EET 2010
Atunci, de ce nu:
mine operator+ (const mine x) {
mine y;
memcpy(y.u, x.u, 10000 * sizeof(int));
return y;
}
Ideea fiind ca la final, y fiind un obiect va fi distrus automat cand iesi din main prin apelul destructorului. Ce faci tu e sa creezi un non-obiect in operator+ si banuiesc ca de-aia nu merge.
On Mar 6, 2010, at 4:29 PM, marius Dragus wrote:
> Pai operatorul + nu ar trebui sa modifice obiectul curent.
> De exemplu pe stringuri:
>
> string x ="ana";
> string y ="are";
> string z = x+y;
>
> cout<< x; //afiseaza "ana", x nu e modificat.
>
>
> 2010/3/6 Dan-George Filimon <dangeorge.filimon at gmail.com>
> Nu inteleg de ce ai in definitia operatorului + o noua alocare de memorie.
> De ce nu folosesti pointerul this?
>
> Cand faci un operator ca + m-as gandi ca ai ceva de genul:
> mine operator+(const mine x) {
> memcpy(this->u, x.u, 10000 * sizeof(int));
> return *this;
> }
>
> Asta nu ar face ce vrei?
>
> On Mar 6, 2010, at 4:20 PM, marius Dragus wrote:
>
> > Salut,
> >
> > Incerc sa scriu o clasa "mine" in C++ care sa permita operatorul +.
> > Problema este ca fiecare obiect aloca dinamic un array, iar o operatie de genul x =a +b+c ar cauza memory leak-uri.
> >
> > Cum s-ar putea face asta?
> >
> > Mai jos este codul. Mentin un contor al constructorilor/destructorilor, si se vede evident ca se obtin memory leakuri.
> >
> > Mersi,
> > Marius
> >
> > /*************************CODE*********************/
> >
> > #include <iostream>
> >
> > int count = 0;
> > using namespace std;
> >
> > struct mine
> > {
> > int * u;
> > mine()
> > {
> > u = new int[10000];
> > count++;
> > }
> >
> > ~mine()
> > {
> > delete[] u;
> > count--;
> > }
> >
> > mine & operator=(const mine & x)
> > {
> > //cout << "assign" << endl;
> > u = x.u;
> > }
> >
> >
> > };
> >
> > mine& operator+(const mine & x, const mine &y)
> > {
> > mine * ret = new mine;
> > return *ret;
> > }
> >
> > int main()
> > {
> >
> > mine a, b, c, d;
> > mine e;
> >
> >
> > for (int i = 0; i<10; i++)
> > {
> > e = a + b + c + d;
> >
> > }
> >
> > cout << count << "\n"; // afiseaza 35 desi ar trebui sa fie 5
> >
> > return 0;
> > }
> >
> > _______________________________________________
> > cdl-studenti mailing list
> > cdl-studenti at lists.rosedu.org
> > http://lists.rosedu.org/listinfo/cdl-studenti
>
> _______________________________________________
> cdl-studenti mailing list
> cdl-studenti at lists.rosedu.org
> http://lists.rosedu.org/listinfo/cdl-studenti
>
> _______________________________________________
> cdl-studenti mailing list
> cdl-studenti at lists.rosedu.org
> http://lists.rosedu.org/listinfo/cdl-studenti
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.rosedu.org/pipermail/cdl-studenti/attachments/20100306/a788c96e/attachment.htm>
More information about the cdl-studenti
mailing list