C++ -- why the operator= return a reference to *this rather than an object to *this? -


class myclass {   public:     ...     myclass & operator=(const myclass &rhs); // return myclass&     ...   } 

why not

class myclass {   public:     ...     myclass  operator=(const myclass &rhs); // return myclass     ...   } 

is reason more efficient return reference in case?

thank you

// * updated *

i think found key reason follows:

int i1, it2, i3; (i1 = i2) = i3; // i3 assigned i1 

if return type of operator= myclass rather myclass&, following statement doesn't perform same internal data type.

myclass mc1, mc2, mc3;  (mc1 = mc2) = mc3; 

it considered practice following rules used built-in types.

// *** update ***  #include "stdafx.h" #include <iostream>  using namespace std;  int _tmain(int argc, _tchar* argv[]) {     int i1, i2, i3;      i1 = 0;     i2 = 2;     i3 = 3;      (i1 = i2) = i3;      cout << "i1: " << i1 << endl;     cout << "i2: " << i2 << endl;     cout << "i3: " << i3 << endl;      return 0; }  // output vs2010 /* i1: 3 i2: 2 i3: 3 */ 

what mean "why not"? you. if want, can return copy of object instead of reference. there's nothing wrong that, except might indeed prove less efficient.

in many cases people prefer return reference because closer semantics of built-in assignment operator. built-in operator returns lvalue, means can write code like

int a, b = 0; int *p = &(a = b); // `p` points `a` 

admittedly not useful, still if want preserve lvalue semantics, need return reference assignment operator.

update

your updated example incorrect. (i1 = i2) = i3 expression leads undefined behavior, not "i3 assigned i1" seem believe. true fact assignment operator returns lvalue allows compile expressions (i1 = i2) = i3. however, specific expression useless since behavior undefined.

in case of user-defined assignment, in (mc1 = mc2) = mc3 example, behavior defined still far being useful. why want that?


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -