250x250
Notice
Recent Posts
«   2024/07   »
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 31
관리 메뉴

일상 코딩

[C++/9.09] 복사 생성자, 복사 초기화 반환값 최적화 본문

C++/따배C++ 09강 연산자 오버로딩

[C++/9.09] 복사 생성자, 복사 초기화 반환값 최적화

polarcompass 2021. 10. 31. 02:00
728x90

Copy Constructor

return Value Optimization

#include<iostream>
#include<cassert>
using namespace std;

class Fraction
{
private:
    int m_numerator;
    int m_denominator;

    // private 영역으로 넣게되면 복사가 안되게 된다.
    // Fraction(const Fraction &fraction) // copy constructor
    //     : m_numerator(fraction.m_numerator),
    //       m_denominator(fraction.m_denominator)
    // {
    //     // 복사 생성자가 얼마나 자주 생성이되는지 알아보는 출력 코드
    //     cout << "copy constructor called" << endl;
    // }

public:
    Fraction(int num = 0, int den = 1)
        : m_numerator(num),
          m_denominator(den)
    {
        assert(den != 0);
        cout << "Normal Constructor" << endl;
    }

    Fraction(const Fraction &fraction) // copy constructor
        : m_numerator(fraction.m_numerator),
          m_denominator(fraction.m_denominator)
    {
        // 복사 생성자가 얼마나 자주 생성이되는지 알아보는 출력 코드
        cout << "copy constructor called" << endl;
    }

    friend std::ostream & operator << (std::ostream & out, const Fraction & f)
    {
        out << f.m_numerator << " / " << f.m_denominator << endl;
        return out;
    }
};

Fraction doSomething()
{
    Fraction temp(1, 2);
    cout << &temp << endl;
    return temp;
};

int main()
{
    Fraction frac{3, 5};

    // copy constructor를 private으로 만들시
    // 복사가 되지 않게 된다.
    // Fraction fr_copy = frac;
    // Fraction fr_copy(frac);

    // 복사 생성자가 호출이 안됨.
    // 컴파일러가 알아서 Fraction{3,10}에서
    // Fraction을 제거 후 안에 있는 3,10만을 
    // 단순 생성자로 넘겼기 때문임.
    Fraction fr_copy{ Fraction{3, 10} };

    cout << frac << " " << fr_copy << endl;

    for (int i = 0; i < 20; i++)
    {
        cout << "-";
    }
    cout << endl;

    // return value optimization
    // 복사 없이 메모리 주소를 그대로 사용하는 것.
    // 혹은 메모리 주소 그대로 넘겨 주는것.
    Fraction result = doSomething();
    cout << &result << endl;
    cout << result << endl;

    return 0;
}
728x90