string - Is it possible to do a swap on return in c++, instead of return by value? -


suppose i'm coding string class in c++ (i know can use library). string length variable , storage space dynamically allocated in constructor , freed in destructor. when main function calls c=a+b (a,b,c strings), operator+ member function creates temporary object stores concatenated string a+b, returns main function, , operator= member function called free string stored in c , copy data temporary string a+b c, , temporary a+b destructed.

i'm wondering if there's way make happen: instead of having operator= copy data a+b c, want swap data pointers of a+b , c, when a+b destructed, destructs original data in c (which want), while c takes result of a+b without needing copy.

i know coding 2-parameter member function settostrcat , calling c.settostrcat(a,b) can this. example, function can coded as:

    void string::settostrcat(const string& a,const string& b){       string tmp(a.len+b.len); int i,j;       for(i=0;i<a.len;i++) tmp[i]=a[i];       for(j=0;j<b.len;i++,j++) tmp[i]=b[j];       tmp[i]='\0'; this->swap(tmp);     }      void string::swap(string& a){       int n=len; len=a.len; a.len=n;       char *s=str; str=a.str; a.str=s;     } 

i omitted definitions of constructor (which allocates len+1 char-type spaces) , operator[] (which returns reference of ith character). swap function swaps data pointers , length variables between *this , tmp, when tmp destructed after swap, data stored in *this (the string c in main function) destructed. *this has in possession (c.str) concatenated string a+b.

i know if there way optimize performance of c=a+b same level. tried c.swap(a+b) , changed return type of a+b string&, receive warning (reference local variable) , gdb shows temporary gets destructed before swap happens, while want other way.

i think question general. in c++ programming, need temporary object store result of function, when assign object in main function, can not copy data use (much faster) swap of pointers instead? neat way of making happen?

in c++11, can writing move constructor. rvalue references added language solve exact problem.

class string {   ...   string(string&& s) : str(nullptr) {     this->swap(s);   }   string& operator=(string&& s) {     this->swap(s);   }   ...   string operator+(string const& other) {     // (your implementation of concatenation here)   }   ... } 

then code not trigger copy constructor or memory allocation, move allocated memory temporary (the thing returned operator+) new object c.

string c = + b; 

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -