I wrote a class in Visual Studio 2017:
class Person
{
public:
Person() {cout << "construtor" << endl; };
Person(istream&a);
Person(const Person&a) :name(a.name), address(a.address) { cout << "copy construtor" << endl; }
~Person() { cout << "destructor" << endl; };
private:
string name;
string address;
}
Person::Person(istream&a)
{
a >> name >> address;
cout << "call fuction" << endl;
}
int main()
{
Person a =Person(cin);
return 0;
}
In my opinions,I think Person(cin)
may create a temporary obeject;It call FunctionsPerson(istream&a)
;Then was a
created by copy construtor.
So I think the debug results should be like this if I enter Jack CN
:
Jack CN
call fuction
copy constructor
destructor
destructor
But the result is amazing actually:
Jack CN
call fuction
destructor
I have seen that copy initialization happens in
using =
to define variable in C++ primer.Why it didn't happen here.I am searching for a long time on net. Someone talked to me that Person a =Person(cin);
equals Person a(cin)
here;When I debugged,they got the same results.
But I thought of a method.I tried to put Person(const Person&a) :name(a.name), address(a.address) { cout << "copy construtor" << endl; }
into private:
.
An amazing things happended.The version of Person a(cin)
successfully compiled and run.The version of Person a =Person(cin);
didn't compile;Person::Person(const Person&a) is Inaccessible
.So if Person a =Person(cin);
equals Person a(cin)
here.Why Person a =Person(cin);
can not be compiled.And if Person a =Person(cin);
did not call copy construtor.Why when I put it into private:
,it went wrong.So I want to know how a
in Person a =Person(cin)
is initializated.
Is there some compiler optimization or my opinion is wrong? I am searching for a long time. But no use. Please help or try to give some ideas how to achieve this. Thanks in advance.