C ++通过引用传递对象

时间:2015-08-28 19:12:16

标签: c++

此代码背后的机制是什么?为什么没有调用复制构造函数?

#include <iostream>
using namespace std;

class Foo{
public:
    Foo(){
        i = 0;
        cout << "Constructor is called " << i << "\n";
    };
    Foo(int is){
        i = is;
        cout << "Constructor is called " << i << "\n";
    }
    Foo(const Foo &f) {
        cout << "Copy constructor is called\n";
    }
    ~Foo(){
        cout << "Destructor is called " << i << "\n";
    };
    int i;
};

void loadobj(Foo &f) {
    f = Foo(1);
    return;
}

int main() {
    // your code goes here
    Foo f;
    loadobj(f);
    return 0;
}

输出:

Constructor is called 0
Constructor is called 1
Destructor is called 1
Destructor is called 1

这是我对整个过程的看法:

在主循环中创建Obj1。然后loadobj调用复制构造函数,在loadobj中创建obj2。这是对的吗?

1 个答案:

答案 0 :(得分:1)

没有涉及复制构造函数。两个默认构造函数和一个赋值。

试图在下面解释:

<void loadobj(Foo &f) {
    f = Foo(1); // Foo(1) is a temporary object 
                // so it calls default constructor with argument = 1, i.e. called with 1
                // Then the temporary is assigned to f.
                // That is NOT a constructor - just an assignment
                // Then calls destrutcor for temporary
    return; 


int main() {
    // your code goes here
    Foo f;  // calls default constructor with no arguments, i.e. called with 0
    loadobj(f);
    return 0; // calls destructor for f
}