2013-06-13 2 views
2

그래서 나는 다음과 같은 클래스이상한 this-> 행동

class Community 
{ 
private: 
    char* Name; 
    char foundationDate[11]; 
    Person* founder; 
    int maxMembersCount; 
    int membersCount; 
    Person* members; 
    static int communitiesCount; 

.....

을하고 난 복사 생성자 구현하려는 :

Community::Community(const Community& other) 
{ 
    this->Name = new char[strlen(other.Name)+1]; 
    strcpy(this->Name,other.Name); 
    strcpy(this->foundationDate,other.foundationDate); 
    this->founder = other.founder; 
    this->maxMembersCount = other.maxMembersCount; 
    this->membersCount = other.membersCount; 
    this->members = new Person[this->maxMembersCount]; 
    this->members = other.members; 
    communitiesCount++; 
} 

을 하지만이 코드는 커뮤니티 A = B라고 말할 때마다 충돌합니다. 그래서이 코드는 합법적 인 것처럼 보이지만 디버깅을 시작할 때 메시지가 있습니다.이 "메모리를 읽을 수 없습니다". 더 많은 코드 예제가 필요하면 저에게 알려주십시오. 저에게 알려주세요.


Community::Community(const char* name , char foundDate[],Person* founder,int maxMembers) { 

    this->Name = new char[strlen(name)+1]; 
    strcpy(this->Name,name); 
    strcpy(this->foundationDate,foundDate); 
    this->founder = new Person(founder->getName(),founder->getEGN(),founder->getAddress()); 
    this->maxMembersCount = maxMembers; 
    this->membersCount = 2; 
    this->members = new Person[this->maxMembersCount]; 
    communitiesCount++; 

}

이 잘 작동 클래스의 기본 생성자입니다 .... 모든

+1

'Name'과'foundationDate'가'null'로 종료되었거나 적절하게 초기화 되었습니까? 또한, 새로운 메모리를'this-> memebers'에 할당하고 포인터를 바로 덮어 씁니다, 그러나 나는 그것이 당신이보고있는 문제를 일으키는 것으로 생각하지 않습니다. –

답변

1

먼저, other.Name는 널 포인터로 가득 확인 종료 문자는 other.foundationDate에 Null로 끝나는 문자열이 포함되어 있습니다. 즉, strlenstrcpy에 대한 좋은 포인터를 전달합니다.

사실 인 경우 할당에있는 B이 모두 액세스 가능한지 확인하십시오.

그게 사실이라면 printf 모든 것입니다. 그리고 정확히 어디 예외가 발생합니다. 또는 컴파일 할 수 있고 오류를 재현하는 전체 코드를 게시하십시오. 두 번째 더블 오브젝트 파괴에 따라 당신의 기억을 삭제하는 동안

this->members = new Person[this->maxMembersCount]; 
this->members = other.members; 

첫 번째 과제는 (만약 당신이 제대로 delete[] members) (사실, 메모리 누수) 아무것도하지 :

또한 여기에 있습니다.

+0

'members' 멤버에 대한 문장이 틀렸다고 생각합니다. 잘못 편집 했습니까? –

+0

복사 생성자와 연산자를 제외한 모든 항목이 완벽합니다. 만약 내가 단지 this-> membersCount = other.membersCount ... –

+0

나는 그것을 전혀 편집하지 않았다고해도 충돌이 난다. 주의 사항은 정확하며, 두 번째 과제는 첫 번째 쓸데없는 것을 렌더링합니다. 버그를 반복 할 수있는 가능한 가장 작은 예제를보고 싶습니다. – Aneri

1

여기에 여러 가지 문제가 있으며, 그 중 일부는 문제의 일부 또는 전부 일 수 있습니다. Name 또는 foundationDate가 null로 끝나는 오른쪽에없는 경우

  • , 그것은 도망 나쁜 메모리를 복사합니다.
  • founder 또는 members이 개체의 소유자 인 경우 소멸자에서 삭제하지 않으면 메모리가 누수되거나 얕은 복사 및 두 번 삭제 등의 다양한 메모리 관련 문제가 발생할 수 있습니다. .

그냥 NamefoundationDatestd::string 다음은 foundermembers이 값이 아닌 포인터를 소유 할 수 있도록,이 문제를 해결합니다. 힙에 절대적으로 할당해야한다면 버그가 발생하기 쉬운 원시 포인터 대신에 shared_ptr과 같은 스마트 포인터를 사용하십시오.