2013-05-07 4 views
0

동적으로 이름을 할당하기위한 코드를 작성했습니다. 나는 그러한 시나리오에서 깊은 사본을 돌봐야한다는 것을 안다. 내가 작성한 것은 내 자신의 버전의 복사 생성자, 복사 할당 연산자 및 소멸자입니다. Move Assignment Operator와 같은 다른 암시 적 함수를 재정의해야합니까? Move Assignment Operator 나 다른 내재적으로 정의 된 멤버 함수 (앞서 언급 한 것 외에는)의 개념이 명확하지 않습니다. 할당 연산자 이동 또는 다른 암시 적 멤버 함수 (있는 경우)를 표시하려면이 코드를 dynName code에 추가하십시오.객체에 대한 할당 연산자

#include <iostream> 

using namespace std; 

class dynName{ 
    char* name; 
    int size; 
    public: 

    dynName(char* name="") 
    { 
     int n=strlen(name)+1; 
     this->name= new char[n]; 
     strncpy(this->name,name,n); 
     size=n; 
     name[size-1]='\0';//NULL terminated 
     cout << "Object created (Constructor) with name : " 
     << name << " at address " << &(this->name) << endl; 
     } 

    dynName(const dynName& Ob)//Copy Constructor 
    { 
     int n=Ob.size; 
     this->name= new char[n]; 
     strncpy(this->name,Ob.name,n); 
     size=n; 
     cout << "Object created(Copy constructor) with name : " 
     << this->name << " at address " << &(this->name) << endl; 
     } 

    //Assignment Operator 
    dynName& operator=(const dynName& ob); 

    ~dynName() 
    { 
     cout << "Object with name " << this->name << " at address " << 
     &(this->name)<<" destroyed" << endl; 
     delete[] name; 
     name=0; //Avoiding Dangling pointer if any 
     } 
    //friend ostream& operator << (ostream& os,const dynName ob); 
    //Will Call Copy Constructor 

    friend ostream& operator << (ostream& os,const dynName& ob); 
    }; 

dynName& dynName::operator=(const dynName& ob) 
{ 
    // check for self-assignment 
     if (this == &ob) 
     cout << "Created with assignment Operator " << endl; 
      return *this; 

     // first we need to deallocate any value that this string is holding! 
     delete[] this->name; 


     this->size = ob.size; 

      // this->name = new char[this->size]; 
      strncpy(this->name, ob.name,this->size); 
      cout << "Created with assignment Operator " << endl; 

    return *this; 
    } 

//ostream& operator << (ostream& os,const dynName ob) 
ostream& operator << (ostream& os,const dynName& ob) 
{ 
    os << "The name ("<< ob.size << " Letters) : " << ob.name << endl; 
    return os; 
    } 

int main() 
{ 

    dynName Ob1("Andrew Thomas"); 
    dynName Ob2; 
    dynName Ob3(Ob1); 
    dynName Ob4; 
    Ob4=Ob1;//Should Call Assignment Operator 
    cout << "\n\n\n"; 
    cout << Ob1; 
    cout << Ob2; 
    cout << Ob3; 
    cout << Ob4; 
    cout << "\n\n\n"; 

    return 0; 
    } 

이 코드의 문제는 이 왜 그렇게 내 복사 할당 연산자 .ANY 도움말을 호출되지 않는 것입니다?

$ ./Trial

Object created (Constructor) with name : Andrew Thomas at address 0x22ac40 
Object created (Constructor) with name : at address 0x22ac30 
Object created(Copy constructor) with name : Andrew Thomas at address 0x22ac20 
Object created (Constructor) with name : at address 0x22ac10 



The name (14 Letters) : Andrew Thomas 
The name (1 Letters) : 
The name (14 Letters) : Andrew Thomas 
The name (1 Letters) : 



Object with name at address 0x22ac10 destroyed 
Object with name Andrew Thomas at address 0x22ac20 destroyed 
Object with name at address 0x22ac30 destroyed 
Object with name Andrew Thomas at address 0x22ac40 destroyed 

감사 Move assignment operator and `if (this != &rhs)` Class&& 무엇을 참조

편집

?

if (this == &ob) 
    cout << "Created with assignment Operator " << endl; 
     return *this; 

만 출력은 return 문이됩니다 if 몸의 일부입니다 : 나는 그냥 참조 Class&

+0

게시 한 코드가 나를 위해 충돌합니다. – jrok

+3

또 다른 깨진 문자열 클래스를 재 작성하지 말고 std :: string 필드를 사용하여 메모리 관리를 처리하십시오. –

+0

여기서 '동적'단어는 제목과 관련이 없으므로 제거되었습니다. 'int main'에서 모든 ObX 객체는 ** 동적이지 않습니다 **. 그들의 내부 내용은 있지만 객체는 그렇지 않습니다. – quetzalcoatl

답변

5

을 즉 당신이 여기 주위에 괄호를 누락 것 같다 .. 내가 이런 종류의 일을 사용한 적이 의미 항상 실행됩니다.

4

복사 연산자를 호출해야하지만 자체 할당 확인 후 항상 반환됩니다.

dynName& dynName::operator=(const dynName& ob) 
{ 
    // check for self-assignment 
     if (this == &ob) 
     cout << "Created with assignment Operator " << endl; 
      return *this; //THIS LINE is not in the if block 

     // first we need to deallocate any value that this string is holding! 
     delete[] this->name; 


     this->size = ob.size; 

      // this->name = new char[this->size]; 
      strncpy(this->name, ob.name,this->size); 
      cout << "Created with assignment Operator " << endl; 

    return *this; 
    } 
+0

코드에 삽입 된 주석은 쉽게 간과됩니다.당신은 대답의 텍스트에서 그것을 정교하게 만들었을 것입니다. – quetzalcoatl