일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 확률
- float
- 백준
- 반응형 웹
- c++
- 미디어 쿼리
- grid
- Photoshop
- 통신사할인
- 알고리즘
- 강화학습
- pandas
- c
- Gap
- 수학
- 포토샵
- JSX
- 상태
- transform
- skt membership
- REM
- stl
- 소수
- spring
- Codility
- Javascript
- SK바이오사이언스
- CSS
- box-sizing
- react
Archives
- Today
- Total
sliver__
[Mastering C++ Programming] - unique_ptr 본문
728x90
- unique_ptr 스마트 포인터는 auto_ptr과 정확히 동일한 방식으로 작동하지만 unique_ptr이 auto_ptr에 의해 도입된 문제를 해결한다는 점만 다릅니다.
- 따라서 unique_ptr은 C++11부터 auto_ptr을 대체합니다.
- unique_ptr 스마트 포인터를 사용하면 하나의 스마트 포인터만 힙 할당 개체를 독점적으로 소유할 수 있습니다.
- 한 unique_ptr 인스턴스에서 다른 인스턴스로의 소유권 이전은 std::move() 함수를 통해서만 수행할 수 있습니다.
- 따라서 이전 예제를 리팩토링하여 auto_ptr 대신 unique_ptr을 사용하도록 합시다.
- 코드 샘플은 다음과 같습니다.
#include <iostream>
#include <string>
#include <memory>
#include <sstream>
using namespace std;
class MyClass {
private:
static int count;
string name;
public:
MyClass() {
ostringstream stringStream(ostringstream::ate);
stringStream << "Object";
stringStream << ++count;
name = stringStream.str();
cout << "\nMyClass Default constructor - " << name << endl;
}
~MyClass() {
cout << "\nMyClass destructor - " << name << endl;
}
MyClass ( const MyClass &objectBeingCopied ) {
cout << "\nMyClass copy constructor" << endl;
}
MyClass& operator = ( const MyClass &objectBeingAssigned ) {
cout << "\nMyClass assignment operator" << endl;
}
void sayHello( ) {
cout << "\nHello from MyClass" << endl;
}
};
int MyClass::count = 0;
int main ( ) {
unique_ptr<MyClass> ptr1( new MyClass() );
unique_ptr<MyClass> ptr2( new MyClass() );
ptr1->sayHello();
ptr2->sayHello();
//At this point the below stuffs happen
//1. ptr2 smart pointer has given up ownership of MyClass Object 2
//2. MyClass Object 2 will be destructed as ptr2 has given up its
// ownership on Object 2
//3. Ownership of Object 1 will be transferred to ptr2
ptr2 = move( ptr1 );
//The line below if uncommented will result in core dump as ptr1
//has given up its ownership on Object 1 and the ownership of
//Object 1 is transferred to ptr2.
// ptr1->sayHello();
ptr2->sayHello();
return 0;
}
- 결과는 아래와 같습니다.
./a.out
MyClass Default constructor - Object1
MyClass Default constructor - Object2
Hello from MyClass
Hello from MyClass
MyClass destructor - Object2
Hello from MyClass
MyClass destructor - Object1
728x90
'CS > C++' 카테고리의 다른 글
[Mastering C++ Programming] - weak_ptr / Circular dependency (0) | 2022.12.07 |
---|---|
[Mastering C++ Programming] - shared_ptr (0) | 2022.12.07 |
[Mastering C++ Programming] - auto ptr (0) | 2022.12.07 |
[Mastering C++ Programming] - Smart Pointer (0) | 2022.12.07 |
[Mastering C++ Programming] - Issues with raw pointers (0) | 2022.12.07 |
Comments