我有以下代码:
#include<iostream>
using namespace std;
class A{
int size;
double *arr;
public:
A(int len):size(len)
{
cout<<"ctor called"<<endl;
arr=new double[size];
}
A(const A &rhs)
{
cout<<"calling copy ctor"<<endl;
size=rhs.size;
arr=new double[size];
}
~A()
{
cout<<"calling dtor"<<endl;
delete[] arr;
arr=NULL;
size=0;
}
};
A createVector()
{
cout<<"Creating object"<<endl;
A a(10);
cout<<"returning after creating object a"<<endl;
return a;
}
void foo(A v)
{
cout<<"Class A object rcvd"<<endl;
//return v;
}
int main()
{
A a=createVector();
cout<<"a has been rcvd"<<endl;
foo(a);
return 0;
}
我有以下输出:
Creating object
ctor called
returning after creating object a
a has been rcvd
calling copy ctor
Class A object rcvd
calling dtor
calling dtor
我在使用createVector()函数时遇到麻烦。当我按值返回对象时,应调用其复制构造函数,但在行与行之间看不到任何输出
returning after creating object a
a has been rcvd
为什么没有调用复制构造函数?
(当我将rcvd对象作为值传递给foo()时,将调用Copy构造函数)