C++/Syntax 2021. 3. 15. 23:29

얕은 복사(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 인스턴스에서 소멸자를 호출할 때 해제된 메모리를 이후에 다시 사용하려고 하므로 런타임 에러가 발생한다.

'C++ > Syntax' 카테고리의 다른 글

C++ delete  (0) 2021.03.15
C++ 깊은 복사(Deep Copy)  (0) 2021.03.15
C++ 함수 포인터 (Function Pointer)  (0) 2021.03.12
C++ 인라인 함수 (Inline Function)  (0) 2021.03.12
C++ 레퍼런스 (Reference, 참조)  (0) 2021.03.12