So i have a weird problem that isnt exactly an error, its just something im not understanding. i have the following peice of code and the functions it calls. What happens is when the indicated line is run, i get an output telling me the 2nd constructor has been called, which is fine, then i get another line telling me the coppy constructor has been called. Thats no so fine, so i worked out its because im returning a pointer to an instance of the class. Im not sure why it needs to call the copy constructor, i had thought that a pointer was simply a storage unit for a memory address of the thing it points to, in this case an instance of DNA.
//in main.cpp
DNA Mate = *(testDNA.CrossoverMutate(testDNA2));
//in DNA.cpp
DNA* DNA::CrossoverMutate(DNA& refMate)
{
unsigned int* child = new unsigned int[m_iChromeLength];
DNA* mate = &refMate;
SetCrossoverPoint(m_iCrossoverPoint);
if(m_RanGen->IRandom(1, 100) <= m_iCrossoverChance)
{
cout<<"Crossover Triggered"<<endl;
for(unsigned int i=0; i<m_iChromeLength; i++)
{
if(i < m_iCrossoverPoint)
child[i] = m_iGenes[i];
else
child[i] = mate->GetGene(i);
}
}
else
for(unsigned int i=0; i<m_iChromeLength; i++)
child[i] = m_iGenes[i];
//Mutate
for(unsigned int i=0; i<m_iChromeLength; i++)
if(m_RanGen->IRandom(1, 100000) < m_fMutateChance * 1000) //max number to generate should always be 2 0's more than multiplyer, so that it makes a percentage.
{
if(m_iGenes[i] == 1)
child[i] = 0;
else
child[i] = 1;
}
DNA* newdna = new DNA(child, m_iChromeLength, m_fMutateChance, m_iCrossoverChance, *m_RanGen); //Constructor 2
return newdna;
}
So what it now comes down to, is how do i return an instance of a class, without having to create it twice. For instance i return a pointer to a class and it calls the copy constructor, i therefor assume that its creating it again. I return a reference, then the instance of the class goes out of scope because the function ends, i return an actual instance of the class and im pretty sure that creates it twice, because it calls the copy constructor.
The reason i dont want it being created twice is that its obv a drain on resources and i have no way to un-allocate the memory after the function has ended. Is that even a problem? i would imagine so because i havnt called a destructor.
So yea, im slighlty confused, help would be muchly appriciated.
EDIT:: I also forgot to mention that i have written a custom copy constructor and that being another reason why i dont want it being called.