소멸자, 코드 스타일, 스타일 오류 문구 해석
1-7주차 과제 하다가
// TODO: Phone 클래스 구현
// - displayBrand()와 showFeature() 순수 가상 함수를 포함하도록 구현하세요
// - 소멸자를 반드시 virtual로 선언하세요
1-6강의 영상에서 소멸자라는 키워드를 본 기억이 없어서 처음 소멸자라는 개념을 접하고 당황했음.
클래스 구현 및 순수 가상 함수를 구현하는 것은 1-6강의 영상에 나온 것을 그대로 따라하면 됨.
하지만 소멸자는 그렇지 않았음.
소멸자(destructor)
소멸자는 객체가 사라질 때 자동으로 호출되는 특수한 함수를 말한다.
class Phone
{
public:
virtual ~Phone() = 0; // 순수 가상 소멸자
};
// 순수 가상 소멸자는 반드시 본체 구현도 필요하다!
Phone::~Phone() {}
소멸자가 필요한 이유
virtual 소멸자를 사용하면, 자신 클래스의 메모리 누수를 막기 위해서 쓴다.
메모리 누수 : 메모리(RAM)에서 저장 공간을 사용하기 위해 프로그램이 공간을 빌려갔는데, 정작 다 쓰고나서 제자리에
돌려놓지 않아서 발생하는 문제다.
// TODO: main 함수 구현
// - Phone* 타입의 배열을 생성하여 Samsung, Apple, Xiaomi 객체를 저장
// - 반복문을 사용하여 각 객체의 displayBrand()와 showFeature()를 호출
// - 반복문을 사용하여 메모리 해제를 위해 delete 호출
위 문제를 해결하기 위해 내가 작성한 코드는 아래와 같다.
int main() {
Phone* phones[3];
Samsung samsung;
Apple apple;
Xiaomi xiaomi;
phones[0] = &samsung;
phones[1] = &apple;
phones[2] = &xiaomi;
for (int i = 0; i < 3; i++) {
phones[i]->displayBrand();
phones[i]->showFeature();
}
for (int i = 0; i < 3; i++) {
delete phones[i];
}
return 0;
}
그러자 다음과 같은 오류가 발생하였다.

발생한 이유 : delete로 삭제해서는 안될 메모리를 delete했기 때문에 Visual Studio 내부에서 자체적으로 중단한 것.
delete는 스택 객체를 삭제할 수 없다고 한다.
delete는 오직 new로 만든 객체만 삭제할 때 사용하는 키워드라고 한다.
Phone* phones[3];
phones[0] = new Samsung();
phones[1] = new Apple();
phones[2] = new Xiaomi();
for (int i = 0; i < 3; i++) {
phones[i]->displayBrand();
phones[i]->showFeature();
}
for (int i = 0; i < 3; i++) {
delete phones[i];
}
다음과 같이 작성하면 오류 없이 실행된다.
Google C++ Style Guide
https://google.github.io/styleguide/cppguide.html
Google C++ Style Guide
Google C++ Style Guide Background C++ is one of the main development languages used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn ca
google.github.io
https://github.com/cpplint/cpplint
GitHub - cpplint/cpplint: Static code checker for C++
Static code checker for C++. Contribute to cpplint/cpplint development by creating an account on GitHub.
github.com
Should have a space between // and comment
원인 : 코드와 // 주석 사이에 공백 칸이 2개 미만이어서 발생
해결법 : 코드 // example 처럼 코드와 // 주석 사이의 공백을 2칸 만들면 해결
Should have a space between // and comment
원인 : // 주석 뒤에 공백 없이 바로 주석을 달아서 발생
해결법 : // example 처럼 // 뒤에 공백을 한칸 뛰어준 다음 주석을 작성하면 해결
Tab found; better to use spaces
원인 : 줄에 탭이 발견되면 발생
해결법 : 탭을 모두 제거하고, 공백키로 변환해야 해결
An else should appear on the same line as the preceding }
원인 :
}
else { // ❌ 잘못된 형태
해결법 :
} else { // ✔ 올바른 형태
Missing space before else
원인 :
}else { // 처럼 공백 없이 붙여쓴 경우
해결법 :
} else {
Could not find a newline character at t
he end of the file.
원인 : 파일 마지막 줄에서 Enter가 없음.
해결법 : 파일 맨 아래에서 Enter 한 번 눌러 빈 줄 생성.
