2013-05-31 5 views
3

제가복사 생성자라는 여분

#include <cstdlib> 
#include <iostream> 

using namespace std; 
class man{ 
      int i ; 
     public: 
      man(){ 
      i=23; 
      cout << "\n defaul constructir called\t"<< i<<"\n"; 
      } 
      man (const man & X) { 
       i = 24; 
      cout << "\n COPY constructir called\t"<< i<<"\n"; 
      }  
      man & operator = (man x) { 
       i = 25; 
       cout << "\n = operator called\t"<< i<<"\n"; 
       return *this; 
      }  
     }; 

int main(int argc, char *argv[]) 
{ 

    man x; 
    cout <<"\n ----------\n"; 
    man y = x; 
    cout <<"\n ----------\n"; 
    x=y; 


    return 0; 
} 

가 출력

defaul constructir called 23 

---------- 

COPY constructir called 24 

---------- 

COPY constructir called 24 

= operator called 25 

이 출력은 X = Y의 세 번째 통화 이상한에 도시 이상한 행동을 표시하는 프로그램을 가지고;

왜 새 개체를 만들지 않았지만 이전 개체로 작업 할 때 불리는 복사본 구성 자의 추가 인쇄가 있습니다.

는 중간에 임시 개체의 becuase 그래 내가 여기에 그들을 막을 수 있다면 ....

답변

3
man& operator =(man x); 

귀하의 매개 변수는 부산물 인수 소요되며, 그렇게되면 그것은 복사 생성자를 호출합니다. 이것이 불필요한 전화의 원인입니다. 사본을 피할 참조하여 인수를 전달,하지만 당신은 임시직을 통과 할 수 없습니다 (일반적으로 우변라고도 함) :

struct man 
{ 
    man& operator =(man& x) { return *this; }; 
}; 

int main() 
{ 
    man a, b; 

    a = b;  // works 
    a = man(); // error: no viable overloaded '=', 
       // expected an l-value for 1st argument 
} 

모두의 복사 건설을 허용합니다 const를 참조하여 전달 값 및 환율 :

man& operator =(man const& x); 
//     ^^^^^ 
12

이 할당 연산자는 값으로 인수 걸리기 때문에입니다. 대신 const 참조로 가져올 수 있습니다.

+0

감사합니다. @OilCharlesworth. – MAG