0

I've tried to understand what is the purpose of reference returning in this code ? Is it just because returning reference is much faster than copy or is there something else more important ??

class Container
{
    public:
        int Elems;
        int * data;

        Container(int n):Elems(n){data=new int[Elems];}
        Container  operator= (const Container &rhs);
};

Container & Container:: operator= (const Container & rhs) 
{// I deleted the & and I can still compiled and make such things (a=b=c)
    if(this!=&rhs)
    {
        if(data!=NULL)
                {
            delete [] data;
        }   
            Elems=rhs.Elems;
            data=new int[Elems];
            for(int i=0;i<Elems;i++)
                data[i]=rhs.data[i];
    }

        return *this;
}
Sqeaky
  • 1,876
  • 3
  • 21
  • 40
L-caesar
  • 75
  • 1
  • 7

2 Answers2

0

Yes, it's to avoid unneeded copies. In the case of this particular class, though, it's needed for correctness, as there's no proper copy constructor. Default copying instances of this class will result in multiple instances sharing the same data member, and will likely result in multiple deletes.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • thanks for your relpy , but I Coult understand the part of your answer." Default copying instances of this class will result in multiple instances sharing the same data member, and will likely result in multiple deletes." I mean If I couldnt write & there, when I delete part of data in c object , it is also removed through b and a objects ? – L-caesar May 30 '13 at 13:09
  • If you write a class with a member that's a pointer to allocated memory, you have to be careful that the pointer never gets leaked or double-deleted. Often this means you need to define the destructor and the copy constructor as well as operator=(). If you don't define a copy constructor (and you don't, that's an assignment function) then you get a default copy constructor that copies the object bit-for-bit; then you'd have two objects that both pointed to the same `data` array, which is going to lead to double-deletion eventually (or leaks, if nothing ever deletes the array.) – Ernest Friedman-Hill May 30 '13 at 13:14
  • sorry for miss explanation assume that there is destructor and copy constructor , I didnt write them since I just wonder the this part of my code, but you're right I should have explained that. – L-caesar May 30 '13 at 13:25
0

In C++ function signatures do not depend on the return type, so the return is ignored when overloading.

Before C++11, returning a value instead of a reference would incur in copy overhead.

Claudio
  • 10,614
  • 4
  • 31
  • 71
  • Returning by value here would have to return a copy, in C++11 or earlier. You can't implicitly move from `*this`, or elide the copy. – Mike Seymour May 30 '13 at 13:21