Still working on the same code as my previous post, I noticed something gone wrong (memory leak) and I discovered the following code didn't work like I expected:
class A
{
public:
A()
{
std::cerr << "A();\n";
}
~A()
{
std::cerr << "~A();\n";
}
};
void function(A instance = A())
{
A *a = new A(instance);
delete a;
}
int main()
{
function();
}
I would say, the function accepts an object, passes this to the copy-constructor of A and allocates a new A with it. Not the case. This is what it outputs:
A();
~A();
~A();
However, when you consider the following code:
class A
{
public:
A()
{
std::cerr << "A();\n";
}
~A()
{
std::cerr << "~A();\n";
}
};
void function(A instance = A())
{
A *a = new A;
*a = instance;
delete a;
}
int main()
{
function();
}
This DOES work like expected, output is:
A();
A();
~A();
~A();
Am I overseeing something? I think this is rather peculiar.
Thanks.