Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- baekjoon
- function
- raw data
- 오블완
- 문자열
- OOP
- 백준
- 함수
- predictive analysis
- assignment operator
- 티스토리챌린지
- C++
- Pre-processing
- Deep Learning
- vscode
- 반복문
- pass by reference
- Python
- string
- const
- 파이썬
- programming
- Data Science
- 알고리즘
- array
- 포인터
- Class
- Object Oriented Programming
- 배열
- pointer
Archives
- Today
- Total
Channi Studies
[C++] 함수 혹은 메소드에서 객체의 불필요한 복사를 방지하기 본문
객체는 꽤나 큰 메모리를 요구하기 때문에,
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 객체로 복사된 뒤, 함수 호출의 종료와 함께 스택에서 제거되면서 소멸하는 것 입니다.
'C++ > 객체지향 프로그래밍 (OOP)' 카테고리의 다른 글
[C++] Shallow Copying & Deep Copying | 얕은 복사 & 깊은 복사 (1) | 2023.12.29 |
---|---|
[C++] 클래스 멤버 접근 제한자 | Class Member Access Modifiers (1) | 2023.12.29 |
[C++] 생성자 초기화 리스트 (Constructor Initialization List), 생성자 오버로딩 (0) | 2023.12.28 |
[C++] 헤더가드 (header guards) | #pragma once, #ifndef (2) | 2023.12.28 |
[C++] 클래스 멤버 접근하기 (Accessing Class Members) (0) | 2023.12.26 |