객체를 반환하는 3가지 형태

1. 정적으로 생성한 객체 반환

TestInstance TTest::getTestInstance(int i) {
    TestInstance test_instance{i};
    return test_instance;
}
int main()
{
    std::cout << "Hello, World!" << std::endl;
    TTest t;

    TestInstance t2 = t.getTestInstance(1);
    t2.helloInstance();
    
    std::cout << "Bye, World!" << std::endl;
    return 0;
}
Hello, World!
TTest new
TestInstance new 1
TestInstance delete 1
TestInstance hello 1
Bye, World!
TestInstance delete 1
TTest delete

TestInstance는 새로운 메모리에 복사되고 getInstance 안에서 생성한 객체는 바로 소멸된다. 

 

2. 동적으로 생성한 객체 반환

TestInstance* TTest::getTestInstanceDynamic(int i) {
    TestInstance *t = new TestInstance{i};
    return t;
}
int main()
{
    std::cout << "Hello, World!" << std::endl;
    TTest t;

    TestInstance *t2 = t.getTestInstanceDynamic(1);
    // delete t2;

    std::cout << "Bye, World!" << std::endl;
    return 0;
}
Hello, World!
TTest new
TestInstance new 1
Bye, World!
TTest delete

동적으로 생성 후 delete를 하지 않으면 종료될 때까지 소멸되지 않는다.

//delete 주석해제시
Hello, World!
TTest new
TestInstance new 1
TestInstance delete 1
Bye, World!
TTest delete

new를 사용하면 delete를 꼭 의식해야 한다.

 

3. 스마트 포인터로 생성한 객체 반환

std::unique_ptr<TestInstance> TTest::getTestInstanceSmart(int i) {
    std::unique_ptr<TestInstance> t = std::make_unique<TestInstance>(i);
    return t;
}
int main()
{
    std::cout << "Hello, World!" << std::endl;
    TTest t;

    unique_ptr<TestInstance> t2 = t.getTestInstanceSmart(1);

    std::cout << "Bye, World!" << std::endl;
    return 0;
}
Hello, World!
TTest new
TestInstance new 1
Bye, World!
TestInstance delete 1
TTest delete

특정 타이밍에 delete 해야 하는 코드가 아니라면 context가 끝날 때 알아서 delete를 수행해 주는 스마트 포인터가 안정적이다.


TTest.h/cpp, TestInstance.h/cpp 코드

더보기
//TTest.h
class TTest {
public:
    TTest();
    ~TTest();

    TestInstance getTestInstance(int i);
    TestInstance* getTestInstanceDynamic(int i);
    std::unique_ptr<TestInstance> getTestInstanceSmart(int i);
};
#include "TTest.h"

TTest::TTest() {
    cout << "TTest new" << endl;
}

TTest::~TTest() {
    cout << "TTest delete" << endl;
}

TestInstance TTest::getTestInstance(int i) {
    TestInstance test_instance{i};
    return test_instance;
}

TestInstance* TTest::getTestInstanceDynamic(int i) {
    TestInstance *t = new TestInstance{i};
    return t;
}

std::unique_ptr<TestInstance> TTest::getTestInstanceSmart(int i) {
    std::unique_ptr<TestInstance> t = std::make_unique<TestInstance>(i);
    return t;
}
//TestInstance.h
class TestInstance {
public:
    int idx;
    TestInstance(int i);
    ~TestInstance();
    void helloInstance();
};
#include "TestInstance.h"

TestInstance::TestInstance(int i) : idx(i) {
    cout << "TestInstance new " << idx << endl;
}

TestInstance::~TestInstance() {
    cout << "TestInstance delete " << idx << endl;
}

void TestInstance::helloInstance() {
    cout << "TestInstance hello " << idx << endl;
}