2017-06-02 102 views
0

当我在下面的代码中调用f1时,是否应该调用构造函数? 我看到“this”指针在对象b(参数为f1)中是不同的,这意味着创建了一个新对象,但是我没有看到b的构造函数中的打印。 但是有调用析构函数,任何人都可以解释吗?在VC 2012所示将对象传递给函数不会导致构造函数调用

class A 
{ 
    int k ; 
public: 
    A(int i) 
    { 
     k=i; 
     printf("%d inside [%s]ptr[%p]\n",k,__FUNCTION__,this); 
    } 
    ~A() 
    { 
     printf("%d inside [%s]ptr[%p]\n",k,__FUNCTION__,this); 
    } 
    void A_fn() 
    { 
     printf("%d inside [%s]ptr[%p]\n",k,__FUNCTION__,this); 
    } 
}; 
void f1(A b) 
{ 
    b.A_fn(); 
} 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
    A a(10); 
    f1(a); 
    return 0; 
} 

输出:

10 inside [A::A]ptr[00B3FBD0] 

10 inside [A::A_fn]ptr[00B3FAEC] 

10 inside [A::~A]ptr[00B3FAEC] 

10 inside [A::~A]ptr[00B3FBD0] 

Press any key to continue . . . 
+2

添加在拷贝构造函数的注释和检查... – Nipun

回答

2

因为当按值传递一个对象,该对象被复制,因此拷贝构造将被调用。

0

前面已经指出的那样,你需要一个拷贝构造函数添加到A级。这是应该的样子:

A(const A&) 
{ 
    printf("Inside copy constructor\n"); 
}