C++ 얕은 복사(Shallow Copy)

2021. 3. 15. 23:29·SW개발/C++
반응형

얕은 복사(Shallow Copy)

  • 얕은 복사는 허상 포인터(Dangling pointer) 문제를 일으킬 수 있다.

    #include <iostream>
    #include <cassert>
    
    class MyString
    {
      char*    data_ = nullptr;
      int        len_ = 0;
    
    public:
      MyString(const char* source = "")
      {
        assert(source);
    
        len_ = std::strlen(source) + 1;
        data_ = new char[len_];
    
        for (int i = 0; i < len_; ++i)
          data_[i] = source[i];
        data_[len_ - 1] = '\0';
      }
    
      ~MyString()
      {
        delete[] data_;
      }
    
      char*& getString() { return data_; }
    };
    
    int        main()
    {
      using namespace std;
    
      MyString    hello("Hello");
    
      cout << (int*)hello.getString() << endl;
      cout << hello.getString() << endl;
    
      {
        MyString    copy = hello;
    
        cout << (int*)copy.getString() << endl;
        cout << copy.getString() << endl;
      }
    
      cout << hello.getString() << endl;
    }
    
    /* stdout
    00F2DD50
    Hello
    00F2DD50
    Hello
    ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌ä↕O±▌↨
    */
    
    /* Runtime Error
    Debug Assertion Failed!
    
    Expression : _CrtlsValidHeapPointer(block)
    */
    • copy 인스턴스에서 소멸자를 호출할 때 해제된 메모리를 이후에 다시 사용하려고 하므로 런타임 에러가 발생한다.
반응형
저작자표시 (새창열림)

'SW개발 > C++' 카테고리의 다른 글

C++ delete  (0) 2021.03.15
C++ 깊은 복사(Deep Copy)  (0) 2021.03.15
C++ 복사 생성자(Copy Constructor)  (0) 2021.03.12
C++ 위임 생성자 (Delegating Constructor)  (0) 2021.03.12
C++ 멤버 초기화 리스트 (Member Initializer Lists)  (0) 2021.03.12
'SW개발/C++' 카테고리의 다른 글
  • C++ delete
  • C++ 깊은 복사(Deep Copy)
  • C++ 복사 생성자(Copy Constructor)
  • C++ 위임 생성자 (Delegating Constructor)
Caniro
Caniro
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 전체보기 (321) N
      • SW개발 (269) N
        • Java Spring (6)
        • C++ (186)
        • Python (21)
        • Linux (16)
        • 알고리즘 (13)
        • Git (4)
        • Embedded (1)
        • Raspberrypi (9)
        • React (3)
        • Web (3) N
        • Windows Device Driver (6)
      • IT(개발아님) (47)
        • Windows (26)
        • MacOS (8)
        • Utility (11)
      • 챗봇 짬통 (0)
      • 일상 (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    제외
    스프링 프레임워크 핵심 기술
    java
    dism
    unix
    SFC
    Workspace
    윈도우
    logi options
    citrix workspace
    백기선
    알림
    그림판
    spring
    로지텍 마우스 제스처
    Windows 11
    SunOS 5.1
    Solaris 10
    KakaoTalk
    mspaint
    윈도우 명령어
    시스템 복구
    vscode
    EXCLUDE
    windows
    MacOS
    스프링
    맥북 카카오톡 알림 안뜸
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Caniro
C++ 얕은 복사(Shallow Copy)
상단으로

티스토리툴바