Here I have a C++ code:
#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, Person*> test;
test.insert(pair<string, Person*>("ini_1", new Person(2)));
return 0;
}
Output
Default constructor
- From the output, I would like to know, how I can delete the value of
test
map givennew Person(2)
without coding it like first
Person* per = new Person(2)
test.insert(pair<string, Person*>("ini_1", per));
delete per;
- Without defining like this first
Person* per = new Person(2)
test.insert(pair<string, Person*>("ini_1", per));
Will it lead to undefined behaviour? Can you describe more detail of the undefined behaviour? Especially how does it exist in the memory? Thanks.
- If it is not correct, can I do like this which use
Person
insteadnew Person
? Will it lead to any undefined behaviour?
#include <iostream>
#include <map>
#include <string>
#include <cstdlib>
using namespace std;
class Person {
private:
int year;
public:
Person(int y): year(y)
{ cout << "constructor" << endl;}
Person(const Person& pers)
{
cout << "copy constructor" << endl;
}
~Person()
{
cout << "Destructor " << endl;
}
int get_year() const
{
return year;
}
};
int main()
{
map<string, Person> test;
test.insert(pair<string, Person>("ini_1", Person(2)));
return 0;
}
Output:
constructor
copy constructor
copy constructor
Destructor
Destructor
Destructor
- I don't understand why the constructor ran for once and copy constructor ran for twice. Can you please explain where they happened?
Thanks.