Ja w zasadzie nie piszę w C++, ale mam projekt w C++/CLI i niechcący użyłem składni, której nie rozumiem. Zobrazuję to może poniższym przykładem:
#include <iostream>
using namespace std;
class A
{
char * _name;
public:
A()
{
_name = "default";
cout << "Constructor of A: default" << endl;
}
A(A& other)
{
_name = other._name;
cout << "Copy constructor of A:" << _name << endl;
}
A(A&& other) : _name(other._name)
{
other._name = nullptr;
cout << "Move constructor of A:" << _name << endl;
}
A(char * name)
{
cout << "Constructor of A:" << name << endl;
_name = name;
}
void SayName()
{
cout << _name << endl;
}
~A()
{
cout << "Destructor of A:" << _name << endl;
}
};
int main()
{
A(a);
a.SayName();
}
Mam wątpliwość co do zapisu:
A(a);
Spodziewałem się wywołania konstruktora z jednym parametrem i błędu kompilacji, a dostaje właściwy rezultat
Sukces #stdin #stdout 0s 16064KB
Constructor of A: default
default
Destructor of A:default
Ok czyli jest coś czego nie wiem, ale wygląda ok.
Dziwnie się zrobiło jednak gdy zrobiłem tak:
int main()
{
A a(a);
a.SayName();
}
i wynik jaki dostałem:
Sukces #stdin #stdout 0s 4236KB
Copy constructor of A:AWAVA��AUATL�%v
AWAVA��AUATL�%v
Destructor of A:AWAVA��AUATL�%v
Jak widać wywołał się konstruktor kopiujący, ale nie widać konstruktora, który utworzył obiekt kopiowany.
Czy może mi ktoś wyjaśnić oba te przypadki?