I have the following code to test the flow of the object returned by the local function. Only want to figure out how it works. At the beginning, I thought the returned object would call the copy constructor to initialize the variable tt
in the main function. In this case, this code would result in segmentation fault since I did not do the real copy, e.g. deep copy. But what happens is totally not what I thought. It did not call a copy constructor neither do I encounter a segmentation fault. I really want to know why?
Another experiment is if I add the explicit to the copy constructor, the compiler would report the error for implicit calling the copy constructor. I just do not understand how this function works.
My testing environment is on Ubuntu 16.04.1 with g++ compiler (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
class test{
public:
explicit test(int n);
test(const test& t);
~test();
int getCount(){return count;}
void printChar(int idx){ cout<<data[idx]<<endl; }
void setChar(int idx, char v){ data[idx]=v; }
private:
int *data;
int count;
};
test::test(int n):data(NULL)
{
cout<<"in constructor"<<endl;
data = new int [n];
count =n;
}
test::test(const test& t)
{
cout<<"in copy constructor"<<endl;
}
test::~test()
{
cout<<"delete a test"<<endl;
delete [] data;
}
test getClass()
{
test t(10);
t.setChar(0,'f');
t.setChar(1,'u');
return t;
}
int main()
{
test tt = getClass();
cout<<tt.getCount()<<endl;
tt.printChar(0);
return 0;
}