• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

[14:55] 교수님 코드와 다르게 move constructor도 호출되었는데요.

20.01.24 19:53 작성 조회수 158

1

안녕하세요.

여기서 무브 컨스트럭터는 호출 될 수도 있는 건가요?

리소스의 copy assignment는 사용이 안되는 걸 확인 할 수 있는데

결과가 좀 달려서 여쭤봅니다.

감사합니다.

<메인 전체코드>

// 15_3.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "Timer.h"
#include "AutoPtr.h"
#include "Resource.h"

AutoPtr<ResourcegenerateResource()
{
    AutoPtr<Resource> res(new Resource(10'000'000));

    return res;
}

int main()
{
    using namespace std;
    streambuf* orig_buf = cout.rdbuf();
    //cout.rdbuf(NULL); // disconnect cout from buffer

    Timer timer;

    {
        AutoPtr<Resource> main_res;
        main_res = generateResource();
    }

    cout.rdbuf(orig_buf);
    timer.elapsed();

    return 0;
}

<오토피티알 전체코드>

#pragma once

#include <iostream>
template<class T>
class AutoPtr
{
private:
    T* m_ptr;

public:
    AutoPtr(T* ptr = nullptr)
        : m_ptr(ptr)
    {
        std::cout << "AutoPtr default constructor " << std::endl;
    }

    ~AutoPtr()
    {
        std::cout << "AutoPtr destructor " << std::endl;

        if (m_ptr != nullptrdelete m_ptr;
    }

    //AutoPtr(const AutoPtr& a)
    //{
    //  std::cout << "AutoPtr copy constructor " << std::endl;

    //  // deep copy
    //  m_ptr = new T;
    //  *m_ptr = *a.m_ptr;
    //}

    //AutoPtr& operator=(const AutoPtr& a)
    //{
    //  std::cout << "AutoPtr copy assignment " << std::endl;

    //  if (&a == this)     // preent self-assignment
    //      return *this;

    //  if (m_ptr != nullptr) delete m_ptr;

    //  // deep copy
    //  m_ptr = new T;
    //  *m_ptr = *a.m_ptr;

    //  return *this;
    //}

    //AutoPtr(const AutoPtr& a) = delete;
    //AutoPtr& operator=(const AutoPtr& a) = delete;

    AutoPtr(AutoPtr&& a)
        : m_ptr(a.m_ptr)
    {
        a.m_ptr = nullptr;  // really necessary?

        std::cout << "AutoPtr move constructor " << std::endl;
    }

    AutoPtr& operator=(AutoPtr&& a)
    {
        std::cout << "AutoPtr move assignment " << std::endl;

        if (&a == this) // prevent self-assignment
            return *this;
        
        if (!m_ptr) delete m_ptr;

        // shallow copy
        m_ptr = a.m_ptr;
        a.m_ptr = nullptr;  //really necessary?

        return *this;
    }

};

답변 4

·

답변을 작성해보세요.

6

audtn7498님의 프로필

audtn7498

2020.03.07

release 모드에서는 copy와 move constructor를  실행시키지 않는거 같습니다

2

Timer.h와 Resource.h가 없네요.
디버거로 하나하나 찍어보셔야할 것 같습니다.

1

anfdmlrltk11님의 프로필

anfdmlrltk11

2021.01.22

return 에서 release 랑 debug 차이 때문인 것 같네요

1

이게 제가 프로젝트 만들어서 한 번 돌려보고 다시 오겠습니다.