I'm a new comer! It's obvious that when we call a getter function of a class which returns an object (NOT fundamental types), copy constructor of object's class will be run to make a copy of object & after ';' destructor to destruct.
But I've noticed when we don't have any return inside this called getter function, the copy constructor won't be run but NOT about the destructor!!! Why does the destructor run when no object has constructed before?
Now Imagine the time when we have an int counter of total objects of a specific class that pluses 1 inside constructor & copy constructor and minuses 1 inside destructor of the class to count the number of surviving objects. So we could have a wrong number including the problem above.
Look at the example below:
class Test
{
public:
Test()
{
testCounter++;
}
~Test()
{
testCounter--;
}
Test(const Test &)
{
testCounter++;
}
static int getTestCounter()
{
return testCounter;
}
private:
static int testCounter;
};
class Confirm
{
public:
Confirm()
{
counter++;
}
~Confirm()
{
counter--;
}
Confirm(const Confirm &)
{
counter++;
}
Test get()
{
return f;
}
Test result (Test)
{
//we don't have a return value
}
static int getCounter()
{
return counter;
}
private:
static int counter;
Test f;
};
int main()
{ Confirm a;
/*building an object of confirm class which have
an object of Test class in it
(So counter & testcounter, both are 1)*/
Test b;
//(counter is 1 & testcounter is 2)
b = a.get();
/*copy constructor & destructor, both will
be run and the numbers will stayed*/
a.result(b);
/*only destructor will be run because
we have no return value
(So counter is 1 & testcounter is 1)
which is a wrong statistics!!!*/
std::cout<<endl<<Confirm::getCounter()<<endl<<Test::getTestCounter();
//will cout 1 1 instead of 1 2 (wrong statistic)
getch();
return 0;
}
By the way, I could solve the wrong number problem by some other ways buy I just wanted to know the engineering analysis of this strange behavior & how to solve the wrong number problem in this algorithm.