Re: Memory leakage avoidance when using new[]
On 1 Sep, 20:06, Juha Nieminen <nos...@thanks.invalid> wrote:
Barry wrote:
But what about when that pointer points to memory allocated using new
[]?
It depends on the copying policy you want to use.
If copying is disabled, or if a deep copy is always performed, just
use std::vector. No need to reinvent the wheel.
If you want the array to be shared, I think there's a smart pointer
for that purpose in the boost library. You could relatively easily code
one yourself.
If you want the ownership to be transferred, implement your own
auto_array (if you google that name you'll probably find implementations
made by others).
If you want copy-on-write, then you'll have to implement that yourself.
Thanks for your reply. Since I'm still learning, does the code I
provided in my first post avoid memory leakage? I had taught about
using std::vector actually in this fashion -
private:
std::vector<Offspring> offspring;
std::vector<CompirerErrors> compirerErrors;
...
Person& operator=(const Person& person)
{
if(person==this)
return this;
try
{
tempPerson.offspring = person.tempOffspring;
compirerErrors = person.compirerErrors;
}
catch(...)
{
throw PersonException();
}
...
}
But if -
tempPerson.offspring = person.tempOffspring
were to throw an exception here, wouldn't I end up with a Person
object which is in a corrupt state? How should I deal with this.
Thanks again,
Barry