c++ - Why is copy constructor called here? -


i have following code:

template<class t = char> class string { public:      // default constructor     string()         : buffer(nullptr),         len(0)     {         cout << "default constructor" << endl;     }      // constructor     string(const char* s)     {         cout << "constructor (const char*)" << endl;         //...     }      // virtual destructor.     virtual ~string()     {         cout << "destructor" << endl;         len = 0;         delete[] buffer;     }       // copy constructor     string(const string& s)     {         cout << "copy constructor" << endl;         buffer = new t[s.len];         std::copy(s.buffer, s.buffer + s.len, buffer);         len = s.len;     }       // copy assignment operator (uses copy , swap idiom)     string& operator=(string s)     {         cout << "copy assignment operator (copy , swap idiom)" << endl;         std::swap(buffer, s.buffer);         return *this;     }       // move constructor     string(string&& s)     {         cout << "move constructor" << endl;     }       // compound assignment (does not need member,     // is, modify private members)     string& operator+=(const string& rhs)                                 {                                   cout << "operator+=" << endl;                //...          return *this; // return result reference     }      // friends defined inside class body inline , hidden non-adl lookup     // passing lhs value helps optimize chained + b + c     // otherwise, both parameters may const references     friend string operator+(string lhs, const string& rhs)     {         cout << "operator+" << endl;          lhs += rhs; // reuse compound assignment         return lhs; // return result value (uses move constructor)     }   private:      t* buffer;     size_t len;  };   int main() {     string<> s("hello ");     string<> s2("world");      // call copy constructor first?     string<> s3 = s + s2;      return 0; } 

and output is:

constructor (const char*) constructor (const char*) copy constructor operator+ operator+= move constructor destructor 

my question why copy constructor called in:

string<> s3 = s + s2; 

a value copy of s taken friend string operator+(string lhs, const string& rhs), because s not anonymous temporary , therefore not appropriate candidate move construction. taking value copy requires copy constructor.


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -