copy constructor

#include <iostream>

    using namespace std;

    class Person{
    public:
        //default ctor
        Person(){
            cout<<"person default constructor"<<endl;
        }

        //copy ctor
        Person(const Person&){
            cout<<"person copy constructor"<<endl;
        }

    };


    void dummy1(Person p){ //pass by value

    }

    void dummy2(const Person& p){ //pass by reference

    }


    //http://stackoverflow.com/questions/2168201/what-is-a-copy-constructor-in-c
    int main(){
        //call default ctor
        Person p0;
        Person p1 = Person(); //这里只调用一次default ctor, 貌似是被编译器优化了
        //[](http://zh.wikipedia.org/wiki/%E8%A4%87%E8%A3%BD%E5%BB%BA%E6%A7%8B%E5%AD%90)

        //call copy ctor
        Person p2 = p1;
        Person p3(p1);

        //call copy ctor
        dummy1(p0);
        //call nothing
        dummy2(p1);

        return 0;
    }

RioDream
126 声望14 粉丝