1

Some hours ago I read this question in which the user initialized a const object as

const QList warnings = QList() << 0 << 3 << 7;

Indeed, this expression somehow hurt me because going against the concepts I have of const and of overloading operator<<.

I tried to define an operator<< possibly allowing for the mentioned expression and here is what I got:

typedef vector<int> Vect; 
Vect operator<<(Vect v, const int i){ //ByVal v, This way it works, but at which cost? 
    v.push_back(i);                   //v is copied at every call!
    return v;
};      

//Here is where I build the object
const Vect const_vect = Vect() << 1 << 2;  
//it works fine but I see massive overhead due to copies..@_@

//Just for testing
int main() {
    for(auto e = const_vect.begin(); e!=const_vect.end() ; ++e){ 
       cout << *e << " ";
    }
    return 0;
}

The previous code (which is also here) works fine.

The following, on the other hand, is the expression I would have expected from the definition of operator<<:

 Vect& operator<<(Vect& v, const int i){  //ByRef v<-this I would have expected;                                                
    v.push_back(i);                        //however it can't work because receives and 
    return v;                              //returns reference to temporary object.
 };

My question is: what am I missing? is the operator<< defined in QList differently implemented from mine, in particular, can it receive and return ByRef?

Secondly, is perhaps the aforementioned a standard procedure to initialize complex const objects?

Thirdly (maybe inconvenient), how would such an expression handled by the compiler? what is done at compile-time and what at run-time?

Community
  • 1
  • 1
Acorbe
  • 8,367
  • 5
  • 37
  • 66
  • 4
    What you're missing is that operator<< overloads for QList are *member functions*, not free functions. The temporary in initializer doesn't bind to any reference, the operator is being called on it instead. – jrok Nov 07 '12 at 22:20
  • @CharlesBailey, you can't pass temporary objects by reference. The code, in fact, doesn't compile. – Acorbe Nov 07 '12 at 22:26
  • @jrok. Nice. That's good, thanks, I saw the [reference](http://harmattan-dev.nokia.com/docs/library/html/qt4/qlist.html#operator-lt-lt). Therein `operator<<` returns byref a temporary object, which still [can't work](http://ideone.com/KvBkpg). – Acorbe Nov 07 '12 at 22:33
  • 4
    That's a different issue you've got there in the linked code - it's trying to convert a const ref to non-const ref. [This, however, works just fine](http://ideone.com/3dpQw6). – jrok Nov 07 '12 at 22:37

0 Answers0