Print service provided by iDogiCat: http://www.idogicat.com/
home logo





Home > IT > Programming > C++ Programming > iDog's Interview C++ > iDog's Interview C++ Part 2 > Compilers' Different Behaviors on Object Copies in function

Compilers' Different Behaviors on Object Copies in function

iDog

Test program

#include 

using namespace std;


class MyClass
{
private:
    int num;

public:
    MyClass() {
        num = 0;
        cout << "Constructor: " << num << endl;
    }

    MyClass(const MyClass& rhs) {
        num = rhs.num + 1;
        cout << "Copy constructor: " << num << endl;
    }

    MyClass& operator=(const MyClass& rhs) {
        num = rhs.num + 1;
        cout << "Assianment operator: " << num << endl;
    }

    ~MyClass() {
        cout << "Destructor: " << num << endl;
    }
};



MyClass myfunc(MyClass obj) {
    cout << ">>> in func, before creating new obj..." << endl;
    MyClass newObj = obj;
    cout << ">>> in func, after creating new obj..." << endl;

    return newObj;
}


int main()
{
    cout << ">>> before creating obj..." << endl;
    MyClass obj;

    cout << ">>> before calling 1st func..." << endl;
    MyClass obj1 = myfunc(obj);
    cout << ">>> before calling 2nd func..." << endl;
    myfunc(obj);
    cout << ">>> after calling func..." << endl;

    return 0;
}

Results of Visual Studio 2005

>>> before creating obj...
Constructor: 0
>>> before calling 1st func...
Copy constructor: 1
>>> in func, before creating new obj...
Copy constructor: 2
>>> in func, after creating new obj...
Copy constructor: 3
Destructor: 2
Destructor: 1
>>> before calling 2nd func...
Copy constructor: 1
>>> in func, before creating new obj...
Copy constructor: 2
>>> in func, after creating new obj...
Copy constructor: 3
Destructor: 2
Destructor: 1
Destructor: 3
>>> after calling func...
Destructor: 3
Destructor: 0

Results of g++ 3.*

>>> before creating obj...
Constructor: 0
>>> before calling 1st func...
Copy constructor: 1
>>> in func, before creating new obj...
Copy constructor: 2
>>> in func, after creating new obj...
Destructor: 1
>>> before calling 2nd func...
Copy constructor: 1
>>> in func, before creating new obj...
Copy constructor: 2
>>> in func, after creating new obj...
Destructor: 2
Destructor: 1
>>> after calling func...
Destructor: 2
Destructor: 0