본문 바로가기
개발/C, C++

C++ - 임시 객체 (temporary object)

by 피로물든딸기 2021. 10. 27.
반응형

C, C++ 전체 링크

 

FOOD 클래스를 반환하는 함수에 대해 아래의 결과를 보자.

#include <stdio.h>
#include <memory> 
#include <iostream>

using namespace std;

class FOOD
{
private:
	int price = 0;
public:
	FOOD(int p)
		: price(p)
	{
		printf("FOOD created, price : %d\n", price);
	}
	~FOOD() { printf("FOOD deleted, price : %d\n", price); }

	FOOD(const FOOD& food) /* 복사 생성자 */
		:price(food.price)
	{
		printf("FOOD copy, price : %d\n", price);
	}

	FOOD& operator=(const FOOD& food)
	{
		printf("FOOD operator=, price : %d\n", food.price);
		price = food.price;
		return *this;
	}

	virtual void printName() { cout << "FOOD Class" << endl; }
	virtual void printPrice() { cout << this->price << endl; }
	void printLine() { cout << "=================" << endl; }
};

FOOD getFood(int price)
{
	cout << "start getFood\n" << endl;

	FOOD food(price);

	cout << "\nend getFood\n" << endl;

	return food;
}

int main(void)
{
	cout << "start main\n" << endl;

	FOOD fd = FOOD(3000);

	fd = getFood(5000);

	cout << "\nend main\n" << endl;

	return 0;
}

 

main에서 fd를 price가 3000인 객체를 생성한다.

그리고 getFood 함수에서 price가 5000인 객체를 생성하여 fd에 복사한다.

 

객체 복사가 일어나기 때문에 복사 생성자가 호출된다.

이때, 이름 없는 임시 객체가 생성이 된다. 

 

복사가 완료되면 getFood 함수에서 임시 객체원본 객체가 소멸한다.

operator = 연산자가 호출된 후에는 임시 객체가 소멸된다.

(복사 생성자 호출 → 임시 객체 생성 → 원본 객체 소멸 → = → 객체 소멸)

 

즉, 이 과정에서 깊은 복사(deep copy)로 객체가 생성된다.

 

main이 종료된 이후에는 복사된 FOOD도 소멸된다.

 

또한 함수가 반환한 값을 대입하지 않더라도 이름 없는 임시 객체는 생성되고 소멸한다.

int main(void)
{
	cout << "start main\n" << endl;

	/* FOOD fd = FOOD(3000);

	fd = */ getFood(5000);

	cout << "\nend main\n" << endl;

	return 0;
}

 

참고로 Release 모드인 경우에 임시 객체는 생성되지 않는다.

 

반응형

댓글