0

I just learned about the constructor, and there is a question I am not sure, whether Person(10) is actually Person px(10), and then p2 = px. But the printed result is "paramererized constructor!" and "Destructor!" ", there is no "Copy Constructor!". Is the system automatically optimized or I made a mistake?

class Person {
public:

    Person() {
        cout << "default constructor!" << endl;
    }
    
    Person(int a) {
        age = a;
        cout << "paramererized constructor!" << endl;
    }

    Person(const Person& p) {  
        age = p.age;
        cout << "Copy Constructor!" << endl;
    }

    ~Person() {
        cout << "Destructor!" << endl;
    }
public:
    int age;
};

int main()
{
    Person p2 = Person(10);

    return 0;
}
timeil0611
  • 39
  • 1
  • 1
  • 7
  • FYI you can turn off optimization using `-O0` (first one is the letter O, second one is the digit 0) for optimization level 0 – gkhaos May 11 '21 at 16:07
  • 2
    @gkhaos FWIW, that only applies pre C++17. In C++17 this is no longer a compiler optimization but a language feature. – NathanOliver May 11 '21 at 16:09
  • @NathanOliver can you please add some resources that confirm what you are saying? (I searched the web myself, but didn't find anything useful) – gkhaos May 12 '21 at 07:38
  • 1
    @gkhaos See: https://stackoverflow.com/questions/38043319/how-does-guaranteed-copy-elision-work – NathanOliver May 12 '21 at 12:00

0 Answers0