0

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;
}
Jonas
  • 6,915
  • 8
  • 35
  • 53
  • 4
    "In this case, this code would result in segmentation fault" - C++ never promises to segfault. It only gives undefined behavior, which can be pretty much anything up to and including [nasal demons](http://www.catb.org/jargon/html/N/nasal-demons.html). – user2357112 Jun 20 '17 at 06:00
  • 1
    https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization – juanchopanza Jun 20 '17 at 06:06
  • Wouldn't this usage also try and use the (not deleted) move constructor? – Chris Becke Jun 20 '17 at 06:08
  • The real problem is C++ didn't call the copy constructor in the above example code since it didn't print out the text "in copy constructor" which I wrote in the copy constructor. – jason Deacon Jun 20 '17 at 06:09
  • @juanchopanza Thanks a lot. The answer is copy elision. Just don't understand why the compile report error when I add the explicit to copy constructor since compiler choose the copy elision method. – jason Deacon Jun 20 '17 at 08:12
  • @Melebius yes. you are right. – jason Deacon Jun 20 '17 at 08:12

0 Answers0