본문 바로가기
책 정리/Effective C++ 3rd

항목 26. 변수 정의는 늦출 수 잇는 데까지 늦추는 근성을 발휘하자

by ocean20 2020. 1. 15.

생성자 or 소멸자 호출 타입으로 변수정의시 비용발생한다. 쓰지도 않는데 비용이 발생하면 낭비이다.

 

  * 예시

string encryptPassword(const string& password)
{
  string encrypted; // 생성자 호출 비용이 발생하는 타입의 변수

  if(password.length() < MinimumPasswordLength) {
    throw logic_error("password is too short");
  }
  …  // encrypted 변수를 사용하는 부분, 하지만 위에서 예외발생시 encrypted변수는 쓰이지 않으며, 비용만 발생한다.
  return encrypted;
}

  * 개선된 코드

string encryptPassword(const string& password)
{
  …  //길이점검 루틴 위와동일

  string encrypted;  // 변수의 정의를 늦추긴했지만 여전히 비효율적!! 왜 
  encrypted = password;  
  // 생성자호출 + 대입연산자 비용 발생 -> 한번에 초기화해버리는 방법이 좋을것같다. 항목 4. 참조

  encrypt(encrypted);
  return encrypted;

}

  * 추가개선코드

string encryptPassword(const string& password)
{
  …  //길이점검 루틴 위와동일

  string encrypted(password):
  encrypt(encrypted);  // 복사생성자만 비용발생 위 코드보다 효율적
  return encrypted;
}

  * 루프의 경우는?

// case 1
Widget w;
for(int i = 0; i<n; ++i) {
  w = i;
  …
}

// case 2
for(int I = 0 ; i<n; ++i) {
  Widget w;
  w = i;
  …
}

case 1. 생성자 1 + 소멸자 1 + 대입 n

case 2. 생성자 n + 소멸자 n

 

요약정리

  - 변수정의는 최대한 늦추자. 프로그램도 깔끔해지며 효율도 좋아진다.

댓글