B
Barry
Hi there,
I've learned from experience to use an auto_ptr instead of a raw
pointer for my class variables, as follows -
class Person
{
public:
Person(const bool isSingle=true):lover(isSingle?0:new Lover() ){}
private:
const auto_ptr<Lover> lover;
}
since its a very good approach to avoiding memory leaks.
But what about when that pointer points to memory allocated using new
[]?
private:
const auto_ptr<Lover> lover;
const Offspring* offspring;
const CompirerErrors* compirerErrors;
how would you normally deal with such a case with regard to avoiding
memory leaks?
For example -
Person me;
Person imposter;
imposter = me;
might leak when operator=() throws - when calling new, or when
assigning each member of offspring and compirerErrors.
Therefore how should I implement operator=()? How about this as a
generic solution to memory leakage in operator=()?
Person& operator=(const Person& person)
{
if(person==this)
return this;
try
{
Offspring* tempOffspring = new Offspring[noOfOffspring];
CompirerErrors* tempCompirerErrors = new CompirerErrors
[noOfCompilerErrors];
for(int i = 0; i<noOfOffspring;i++)
tempOffspring = person.tempOffspring;
for(int i = 0; i<noOfCompilerErrors;i++)
tempCompirerErrors = person.compirerErrors;
}
catch(...)
{
delete [] tempOffspring;
delete [] noOfOffspring;
throw PersonException();
}
offspring = tempOffspring;
compirerErrors = tempCompirerErrors;
...
}
I've learned from experience to use an auto_ptr instead of a raw
pointer for my class variables, as follows -
class Person
{
public:
Person(const bool isSingle=true):lover(isSingle?0:new Lover() ){}
private:
const auto_ptr<Lover> lover;
}
since its a very good approach to avoiding memory leaks.
But what about when that pointer points to memory allocated using new
[]?
private:
const auto_ptr<Lover> lover;
const Offspring* offspring;
const CompirerErrors* compirerErrors;
how would you normally deal with such a case with regard to avoiding
memory leaks?
For example -
Person me;
Person imposter;
imposter = me;
might leak when operator=() throws - when calling new, or when
assigning each member of offspring and compirerErrors.
Therefore how should I implement operator=()? How about this as a
generic solution to memory leakage in operator=()?
Person& operator=(const Person& person)
{
if(person==this)
return this;
try
{
Offspring* tempOffspring = new Offspring[noOfOffspring];
CompirerErrors* tempCompirerErrors = new CompirerErrors
[noOfCompilerErrors];
for(int i = 0; i<noOfOffspring;i++)
tempOffspring = person.tempOffspring;
for(int i = 0; i<noOfCompilerErrors;i++)
tempCompirerErrors = person.compirerErrors;
}
catch(...)
{
delete [] tempOffspring;
delete [] noOfOffspring;
throw PersonException();
}
offspring = tempOffspring;
compirerErrors = tempCompirerErrors;
...
}