Temporary Object
object 의 이름이 없으면서 stack memory 에 있는 변수이다. 리터럴 변수의 오브젝트 버전이라고 생각한다.
오브 젝트 변수는 해당 라인의 세미콜론(;) 을 만나면 수명이 끝난다.
예제 클레스
#include<iostream>
using namespace std;
class Point
{
public:
int x, y;
Point(int a, int b) : x(a), y(b) { cout << "Point()" << endl; }
~Point() { cout << "~Point()" << endl; }
Point(const Point& p) { cout << "Copy Point()" << endl; }
};
int main()
{
// 일반 object
Point p(1, 2);
// temporary object 선언 법
Point(1, 2); // 세미콜론을 만나면 소멸함
return 0;
}
알게된점 :
1. temporary Object 는 rvalue 이다.
2. temporary Object 는 레퍼런스를 가질 수 없지만 예외적으로 const &Point a1 = Point(1,2) 로 받으면
a1 이 없어질때 까지 없어 지지 않는다.
3. 함수에서 매개변수 보내고 , 값을 return 할때는 복사 생성(Point(const Point& p) { cout << "Copy Point()" << endl;})를 호출한다.
4. 피라미터로 전달하거나 return 할때 temporary object 로 하면 위와 복사 생성자를 호출하지 않는다.
-특히 return 의 경우 Return Value Optimization(RVO) 라고 부른다.
질문
#include<iostream>
using namespace std;
class Point
{
public:
int x, y;
Point(int a, int b) : x(a), y(b) { cout << "Point()" << endl; }
~Point() { cout << "~Point()" << endl; }
Point(const Point& p) { cout << "Copy Point()" << endl; }
};
Point foo()
{
Point p(1, 2);
return p;
}
Point foo2()
{
return Point(1,2);
}
int main()
{
Point p1(0, 1);
cout << "---------1---------\n";
p1 = foo();
cout << p1.y << endl;
cout << "---------2---------\n";
p1 = foo2();
cout << p1.y << endl;
cout << "---------3---------\n";
Point p2(0, 3);
p1 = p2;
cout << p1.y << endl;
cout << "---------4---------\n";
return 0;
}
질문 -
위의 예제에서 왜 foo 는 y 변수가 없어지고 , foo2 는 y 변수가 남아 있는가
상세 내용
https://tastyprogramming.tistory.com/52
Temporary Object (임시객체)
Temporary Object 란? Temporary objects are unnamed objects created on the stack by the compiler. They are used during reference initialization and during evaluation of expressions including standard..
tastyprogramming.tistory.com
댓글