c++ programming - 7th study
TRANSCRIPT
// 1Person(const Person& src)
: height(src.height), weight(src.weight) { }// 2Person(const Person& src){
height = src.height;weight = src.height;
}
int main(){
Person p1(183.4, 78.5);Person p2(p1);
}
5
Person& operator=(const Person& rhs){
if (this == &rhs)return *this;
height = rhs.height;weight = rhs.weight;
return *this;}
int main(){
Person p1(183.4, 78.5), p2(175.6, 68.3);p1 = p2;
}
12
Person p1 Person p2
int roomNum
3
183.4
double height
78.5
double weight
int* room int roomNum
5
175.6
double height
68.3
double weight
int* room
스택(Stack) 메모리 힙(Heap) 메모리
16
Person p1 Person p2
int roomNum
3
183.4
double height
78.5
double weight
int* room int roomNum
5
175.6
double height
68.3
double weight
int* room
스택(Stack) 메모리 힙(Heap) 메모리
주인이 없어진 메모리!(Orphaned Memory)
17
Person p1 Person p
int roomNum
3
183.4
double height
78.5
double weight
int* room int roomNum
3
183.4
double height
78.5
double weight
int* room
스택(Stack) 메모리 힙(Heap) 메모리
printRoom는 방의 정보를 출력하는 함수함수가 호출되면서 얕은 복사로 인해포인터만 복사되고 데이터는 복사되지 않음
18
Person p1
int roomNum
3
183.4
double height
78.5
double weight
int* room
스택(Stack) 메모리 힙(Heap) 메모리
반환 해제된 메모리→ 댕글링 포인터(Dangling Pointer)
printRoom 함수가 리턴하면스택 객체인 p의 소멸자가 호출되면서room 포인터가 가리키는 메모리를 해제함
19
class Person {private:
int* room;int roomNum;double height;double weight;
public:Person() { }Person(int _roomNum, double _height, double _weight)
: roomNum(_roomNum), height(_height), weight(_weight) {room = new int[roomNum];
}~Person() {
delete[] room;}
};
21
Person(const Person& src): roomNum(src.roomNum), height(src.height), weight(src.weight)
{room = new int[roomNum];for (int i = 0; i < roomNum; ++i)
room[i] = src.room[i];}
24
Person& operator=(const Person& rhs) {if (this == &rhs)
return *this;delete[] room;room = nullptr;
height = rhs.height;weight = rhs.weight;roomNum = rhs.roomNum;
room = new int[roomNum];for (int i = 0; i < roomNum; ++i)
room[i] = rhs.room[i];
return *this;}
25
https://github.com/utilForever/ModernCpp/blob/master/ModernCpp/Classes/ruleOfZero.cpp
https://github.com/utilForever/ModernCpp/blob/master/ModernCpp/Classes/ruleOfFive.cpp
27