I am trying to figure out how to better organize my code, so I've made a simple example representing the issue:
Given ClassA and ClassB:
class ClassA
{
public:
ClassA() { cout << "ClassA ctor\n"; }
ClassA(const ClassA &other) { cout << "ClassA copy ctor\n"; }
ClassA& operator=(ClassA other) {
cout << "ClassA assignment\n";
return *this;
}
~ClassA() { cout << "ClassA destructor\n"; }
};
class ClassB {
ClassA mA;
public:
ClassB(ClassA a) : mA(a) {
cout << "ClassB ctor\n";
}
~ClassB() { cout << "ClassB destructor\n"; }
};
Can somebody explain if there is a way why this code works:
void test3(ClassA pA) { cout << "Test3\n"; }
...
test3(ClassA());
producing the output:
ClassA ctor
Test3
ClassA destructor
While this code doesn't:
ClassB b(ClassA());
ClassB constructor is not even being executed in this case (although no error is thrown either).
Is there a way to avoid copy ctor when passing argument by value to a ctor?