Here I a piece of C++ code.
Code 1:
#include <iostream>
#include <map>
#include <string>
#include <cstdlib>
using namespace std;
class Person {
private:
int year;
Person(const Person& pers);
public:
Person(int y): year(y)
{ cout << "Default constructor" << endl;}
~Person()
{
cout << "Destructor " << endl;
}
int get_year() const
{
return year;
}
};
int main()
{
map<string, const Person&> test;
test.insert(pair<string, const Person&>("ini_1", Person(2)));
test.insert(pair<string, const Person&>("ini_2", Person(3)));
cout << "over" << endl;
map<string, const Person&>::iterator iter = test.begin();
while(iter != test.end())
{
cout << iter->first << endl;
cout << "year is equal to: " << iter->second.get_year() << endl;
iter++;
}
system("pause");
return 0;
}
Output 1:
Default constructor
Destructor
Default constructor
Destructor
over
ini_1
year is equal to: 2
Address for value: 0x6ffeb8
ini_2
year is equal to: 3
Address for value: 0x6ffed8
Code 2:
#include <iostream>
#include <map>
#include <string>
#include <cstdlib>
using namespace std;
class Person {
private:
int year;
Person(const Person& pers);
public:
Person(int y): year(y)
{ cout << "Default constructor" << endl;}
~Person()
{
cout << "Destructor " << endl;
}
int get_year() const
{
return year;
}
};
int main()
{
map<string, const Person&> test;
Person per(2);
test.insert(pair<string, const Person&>("ini_1", per));
cout << endl;
cout << "over" << endl;
cout << endl;
map<string, const Person&>::iterator iter = test.begin();
cout << iter->first << endl;
cout << "year is equal to: " << iter->second.get_year() << endl;
system("pause");
return 0;
}
Output 2:
Default constructor
over
ini_1
year is equal to: 2
I have a couple of questions regarding these two pieces of code:
- For code 1 and its result:
1.1. The destructor runs for both "ini_1" and "ini_2", I think the Person class for both of them has been removed. But when I printed out the value for key "ini_1" and "ini_2", why does the member data still exist?
1.2 After the destructor run, what I think is that the Person class would not exist any more. And the value for the map is the const reference of the Person class. The reference is only an alias of Person clas, it should be removed too when the Person class's destructor run. My question is how did it happen even that the destructor run but the reference Person class still existed in the test map's value? Can you show me how does it store in the memory?
- For code 2 and its result:
2.1 For code 2, the destructor did not run compared to code 1. The difference for code 1 and code 2 is that code 1 has one more iteration than code 2. And form the code 1's output we can see, the memory addresses to store the value of "ini_1" and "ini_2" are different. My question is why the destructor run for code 1? Why the destructor did not run for code 2?
Thanks for your time.