1

다음 클래스에서 계약자는 주 함수에서 문자열과 int ("Jan", 24)를 가져와야합니다. 하지만 1과 같은 다른 임의의 정수가 나이로 인쇄되기 때문에 정수가 전달되면 잘못된 것이있는 것 같습니다.동적 메모리 할당 후 생성자에 정수 전달

#include <iostream> 
    #include <string> 
    using namespace std; 

    class Human{ 
    private: 
     string *name; 
     int *age; 
    public: 
     Human(string iname, int iage){ 
      name = new string; 
      age = new int; 

      name = &iname; 
      age = &iage; 
     } 

     void display(){ 
      cout << "Hi I am "<<*name<<" and i am "<<*age<<" years old"<<endl;} 

     ~Human(){ 
      delete name; 
      delete age; 
      cout << "all memories are released"<<endl; 
     } 
    }; 

    int main() 
    { 
     Human *Jan = new Human("Jan",24); 
     Jan->display(); 
     delete Jan; 

     return 0; 
    } 

출력은 다음과 같으며 24 대신 나이가 인쇄됩니다. 내가 내 생성자를 변경하는 경우

Hi I am Jan and I am 1 years old 
    untitled(5417,0x7fff8ed19340) malloc: *** error for object 
    0x7ffeed4c19b8: pointer being freed was not allocated 
    *** set a breakpoint in malloc_error_break to debug 

내가 알고있는 (나이 = 24) 예상대로 작동하지만 위의 코드가 작동 및 인쇄 나이 = 1하지 않는 이유를 알고 관심 다음과 같습니다.

Human(//the same parameter as before) 
    { 
     //the same memory allocation 
     *name = iname; 
     *age = iage; 
     } 

왜 두 번째 질문은 왜곡자가 첫 번째 코드에서 공개되지 않는 이유입니까?

+1

C++이며 Resource Acquisition Is Initialization 또는 RAII를 알고 있어야합니다. – icaptan

답변

5

생성자에서 임시 변수의 주소를 가져 가기 때문에. nameage 필드의 경우

Human(string iname, int iage){ 
    name = new string; 
    age = new int; 
    name = &iname; 
    age = &iage; 
} 

Human("Jan", 24)으로 호출되었을 때. 그 명령이 완료되면

, Jan24의 주소는 더 이상 유효하지 않습니다 - 그들은 아무것도를 가리키는 될 수 있음을 의미합니다. 당신이 당신의 (현재의 임시) 변수의 수명 연장 할 수있는 경우

class Human { 
private: 
    string name; 
    int age; 
... 

대안 솔루션은 다음과 같습니다 :

그냥 값 복사

{ 
    string name = "Jan"; 
    int age = 24; 
    { 
    Human *Jan = new Human(name, age); 
    Jan->display(); 
    delete Jan; 
    } 
    // &name and &age still valid, until closing bracket 
} 
// &name and &age no longer valid 

또는 대안을, 당신은 할당 할 수 그들은 new을 통해 힙에 있지만, 당신은 그들 자신을 돌볼 필요가 있습니다.


변수 범위 지정, 가시성 및 RAII에 관한 Can a local variable's memory be accessed outside its scope? 및 기타 유사한 질문을 참조하십시오.