0

I have the following class and some constructors:

default constructor assigns empty string and 0

copy constructor copies reference's field to the instance's filed

explicit constructor takes in one string and one integer and assigns them to the field

  1. Without the lines between the "//////", the output is like

explicit constructor

default constructor

My understanding is: the right hand side is evaluated first. That is using an explicit constructor. It then creates one entry with default constructor and assigns the fields from the instance constructed with explicit constructor to the instance constructed by the default constructor.

ppl[0] = Person("Mike", 20);

  1. With the lines bwtween "////", the output looks like

explicit constructor

default constructor

explicit constructor

copy constructor

copy constructor

The first two are just like above. How about explcit + copy + copy? I think the explicit is for Person("jo", 10). How to explain the two copy constructor?

    class Person{
    private:
    string name;
    int age;
    public:
    Person(){
      cout<<"default constructor"<<endl;
      name="";
      age = 0;
    }
    Person(const Person &other){
      cout<<"copy constructor"<<endl;
      name = other.name;
      age = other.age;
    }
    Person(string name, int age){
      cout<<"explicit constructor"<<endl;
      this->name = name;
      this->age = age;
    }
    };

    int main(){

    map<int, Person> ppl;

    ppl[0] = Person("Mike", 20);
    ////////////////////////////////////////////
    ppl.insert(make_pair(1, Person("jo", 10)));
    ////////////////////////////////////////////
    return 0;
    }
WriteBackCMO
  • 629
  • 2
  • 9
  • 18
  • 2
    Try with `std::map::emplace`. `make_pair` copies the temporary `Person`. `insert` copies the pair which copies it's member `Person`. – François Andrieux Aug 30 '17 at 18:07
  • 1
    In c++17 you do not even need to make a temporary `Person`. In older standards you can use piecewise construction. See https://stackoverflow.com/questions/27960325/stdmap-emplace-without-copying-value – François Andrieux Aug 30 '17 at 18:17
  • tried with ppl.emplace(1, Person("jo", 10)), one explicit constructor and one copy constructor. I think the explciit is for Person("jo", 10). The copy constructor is to copy temporary Person("jo", 10) to some internal pair? – WriteBackCMO Aug 30 '17 at 18:21

0 Answers0