Is it possible to do swap when returning to C ++ instead of returning by value?

Suppose I encode a string class in C ++ (I know I can use the library). The length of the string is variable and the memory space is dynamically allocated in the constructor and freed in the destructor. When a function maincalls c=a+b( a,b,c- strings), the member function operator+creates a temporary object that stores the concatenated string a+b, returns it to the function main, and then operator=the member function is called to free the line originally stored in cand copy the data from the temporary string a+bto c, and, finally, the temporary a+bwill be destroyed.

I am wondering if there is a way to do this: instead of operator=copying the data from a+bto c, I want it to change the data pointers a+band c, so when it is a+bdestroyed, it destroys the original data in c(this is what we want), and cnow accepts the result a+bwithout having to copy.

I know that encoding a function with two parameters setToStrcatand calling c.setToStrcat(a,b)can do it. For example, a function can be encoded 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;
    }

( len+1 char) operator[] ( i - ). swap *this tmp, , tmp , , *this (String c main), . *this (c.str) a+b.

, c=a+b . c.swap(a+b) a+b String&, ( ), GDB , , , .

, . ++ , , , ( ) ? ?

+4
1

++ 11 , . Rvalue .

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)
  }
  ...
}

, (, +) c.

String c = a + b;
+1

Source: https://habr.com/ru/post/1652270/


All Articles