반응형
깊은 복사(Deep Copy)
하위 항목을 모두 복사하는 것
#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_; } MyString(const MyString& source) { std::cout << "Copy constructor\n"; len_ = source.len_; if (source.data_ != nullptr) { data_ = new char[len_]; for (int i = 0; i < len_; ++i) data_[i] = source.data_[i]; } else data_ = nullptr; } 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; }- 얕은 복사에서 발생했던 문제가 발생하지 않는다.
반응형
'SW개발 > C++' 카테고리의 다른 글
| C++ 변환 생성자(Converting Constructor) (0) | 2021.03.15 |
|---|---|
| C++ delete (0) | 2021.03.15 |
| C++ 얕은 복사(Shallow Copy) (0) | 2021.03.15 |
| C++ 복사 생성자(Copy Constructor) (0) | 2021.03.12 |
| C++ 위임 생성자 (Delegating Constructor) (0) | 2021.03.12 |