2017-09-11 2 views
1
나는 다음과 같은 코드가

:여기에 복사 생성자가 호출되는 이유는 무엇입니까?

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 and swap idiom) 
    String& operator=(String s) 
    { 
     cout << "Copy assignment operator (copy and swap idiom)" << endl; 
     std::swap(buffer, s.buffer); 
     return *this; 
    } 


    // Move constructor 
    String(String&& s) 
    { 
     cout << "Move constructor" << endl; 
    } 


    // compound assignment (does not need to be a member, 
    // but often is, to modify the private members) 
    String& operator+=(const String& rhs)        
    {       
     cout << "operator+=" << endl;  
     //... 

     return *this; // return the result by reference 
    } 

    // friends defined inside class body are inline and are hidden from non-ADL lookup 
    // passing lhs by value helps optimize chained a + b + c 
    // otherwise, both parameters may be const references 
    friend String operator+(String lhs, const String& rhs) 
    { 
     cout << "operator+" << endl; 

     lhs += rhs; // reuse compound assignment 
     return lhs; // return the result by 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; 
} 

그리고 출력은 다음과 같습니다

Constructor (const char*) 
Constructor (const char*) 
Copy constructor 
operator+ 
operator+= 
Move constructor 
Destructor 
내 질문은 왜 복사 생성자는 즉시 호출됩니다

:

String<> s3 = s + s2; 
+0

2. 사본을 삭제하지 않은 이유는 무엇입니까? – juanchopanza

+0

@juanchopanza 반환 값 (rvalue)이 실제로 이동되었습니다. – Nick

+0

@juanchopanza - lhs가 함수에서 반환 값으로 이동합니다. 보장되어있어. – StoryTeller

답변

7

값 복사s 인 것은 본질적으로 s이 아니기 때문에 friend String operator+(String lhs, const String& rhs)이 취합니다. 따라서 익명 성은 임시적이며 이동 건설을위한 적절한 후보자가 아닙니다. 그 가치 사본을 얻으려면 사본 생성자가 필요합니다.

+1

맞습니다. lhs는 복사본입니다 – Nick

+0

@StoryTeller하지만 그 방법 안에 복사본이 필요합니까? – Nick

0

내 생각에 복사 생성자는 + 연산자의 반환 값을 받기 위해 호출됩니다.

관련 문제