Channi Studies

[C++] 함수 혹은 메소드에서 객체의 불필요한 복사를 방지하기 본문

C++/객체지향 프로그래밍 (OOP)

[C++] 함수 혹은 메소드에서 객체의 불필요한 복사를 방지하기

Chan Lee 2023. 12. 29. 15:38

객체는 꽤나 큰 메모리를 요구하기 때문에,

 

Pass by value 방법 혹은 return 값으로 특정 객체를 활용하는 함수나 메소드는 

큰 용량을 낭비하게 됩니다.

 

이럴 때, pass by reference 방법을 사용하면 이를 방지할 수 있습니다.

 

// main.cpp

#include "Practice.h"
#include <iostream>

using namespace std;

int main() {
  Player ricky("Ricky", 100, 0);
  Player super_enemy = create_super_enemy();
  Player ricky2 = another_hero(ricky);

  return 0;
}
// Practice.cpp

#include "Practice.h"
#include <iostream>
#include <string>

using namespace std;

Player::Player(string name_val, int health_val, int xp_val)
    : name{name_val}, health{health_val}, xp{xp_val} {}

Player::Player(const Player &original_hero)
    : name{original_hero.name}, health{original_hero.health},
      xp{original_hero.xp} {}

string Player::get_name() { return name; }
int Player::get_health() { return health; }
int Player::get_xp() { return xp; }

Player::~Player() { cout << "Destructor called for " << name << endl; }

Player create_super_enemy() {
  Player enemy("SUPER ENEMY", 100000, 0);
  return enemy;
}

Player another_hero(Player &source) {
  Player hero2(source.get_name() + "_", source.get_health(), source.get_xp());
  return hero2;
}
// Practice.h
#ifndef PRACTICE_H
#define PRACTICE_H

#include <iostream>
#include <string>

using namespace std;

class Player {
private:
  string name{};
  int health{};
  int xp{};

public:
  // Overloaded Constructors
  Player(string name_val = "None", int health_val = 0, int xp_val = 0);
  Player(const Player &original_hero);
  string get_name();
  int get_health();
  int get_xp();

  // Destructor
  ~Player();
};

#endif // PRACTICE_H

Player another_hero(Player &source);
Player create_super_enemy();

 

Player 객체의 소멸자가 호출될 때를 확인한다면 이해가 쉽습니다.

 

출력 결과

 

Destructor (소멸자)가 Player의 reference를 인자로 받는 another_hero 함수로 인해서 생성된 ricky2 객체에서 1번,

 

create_super_enemy() 함수로 생성되어서 저장된 super_enemy 객체에서 2번,

 

처음에 일반적인 생성된 ricky 객체에서까지 총 3번 호출되는 것이 확인됩니다.

 

 

만약 pass by value로 another_hero 함수를 실행시킨다면 어떻게 될까요?

 

 

Ricky 이름 속성을 가진 객체가 두번 보이죠?

 

가장 먼저 소멸된 Ricky라는 name 속성을 가진 객체는 Ricky_ 이름 속성을 가진 ricky2 객체를 생성하기 위해

일시적으로 생성되고 ricky2 객체로 복사된 뒤, 함수 호출의 종료와 함께 스택에서 제거되면서 소멸하는 것 입니다.