Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++의 포인터, 스마트 포인터 및 공유 포인터

<시간/>

포인터

포인터는 변수의 주소를 저장하는 데 사용됩니다.

구문

Type *pointer;

초기화

Type *pointer;
Pointer = variable name;

함수

  • 포인터는 변수의 주소를 저장하는 데 사용됩니다.
  • 포인터에는 null 값이 할당될 수 있습니다.
  • 포인터는 참조로 전달될 수 있습니다.
  • 포인터는 스택에 자체 메모리 주소와 크기를 갖습니다.

예시

#include <iostream>
using namespace std;
int main() {
   // A normal integer variable
   int a = 7;
   // A pointer variable that holds address of a.
   int *p = &a;
   // Value stored is value of variable "a"
   cout<<"Value of Variable : "<<*p<<endl;
   // It will print the address of the variable "a"
   cout<<"Address of Variable : "<<p<<endl;
   // reassign the value.
   *p = 6;
   cout<<"Value of the variable is now: "<<*p<<endl;
   return 0;
}

출력

Value of Variable : 7
Address of Variable : 0x6ffe34
Value of the variable is now: 6

C++의 스마트 포인터

스마트 포인터는 파일 처리, 네트워크 소켓 등과 같은 메모리 관리로 사용할 수 있는 방식으로 일반 포인터를 만들 수 있는 추상 데이터 유형입니다. 또한 자동 소멸, 참조 카운팅 등과 같은 많은 작업을 수행할 수 있습니다.

C++의 스마트 포인터는 * 및 -> 연산자로 오버로드된 템플릿 클래스로 구현할 수 있습니다. auto_ptr, shared_ptr, unique_ptr 및 weak_ptr은 C++ 라이브러리에서 구현할 수 있는 스마트 포인터의 형태입니다.

예시

#include<iostream>
using namespace std;
// A generic smart pointer class
template <class T>
class Smartpointer {
   T *p; // Actual pointer
   public:
      // Constructor
      Smartpointer(T *ptr = NULL) {
         p = ptr;
      }
   // Destructor
   ~Smartpointer() {
      delete(p);
   }
   // Overloading dereferencing operator
   T & operator * () {
      return *p;
   }
   // Overloding arrow operator so that members of T can be accessed
   // like a pointer
   T * operator -> () {
      return p;
   }
};
int main() {
   Smartpointer<int> p(new int());
   *p = 26;
   cout << "Value is: "<<*p;
   return 0;
}

출력

Value is: 26

C++의 공유 포인터

shared_ptr은 C++ 라이브러리에서 구현할 수 있는 스마트 포인터 형식 중 하나입니다. 원시 포인터와 참조 카운팅(객체, 메모리 블록, 디스크 공간 또는 기타 리소스와 같은 리소스에 대한 참조, 포인터 또는 핸들의 수를 저장하는 기술)에 포함된 포인터의 소유권 구조의 컨테이너입니다. shared_ptr의 모든 사본과 함께.

포함된 원시 포인터가 참조하는 개체는 모든 복사본이 shared_ptr에서 제거될 때만 파괴됩니다.

예시

#include<iostream>
#include<memory>
using namespace std;
int main() {
   shared_ptr<int> ptr(new int(7));
   shared_ptr<int> ptr1(new int(6));
   cout << ptr << endl;
   cout << ptr1 << endl;
   // Returns the number of shared_ptr objects
   // referring to the same managed object.
   cout << ptr.use_count() << endl;
   cout << ptr1.use_count() << endl;
   // Relinquishes ownership of ptr on the object
   // and pointer becomes NULL
   ptr.reset();
   cout << ptr.get() << endl;
   cout << ptr1.use_count() << endl;
   cout << ptr1.get() << endl;
   return 0;
}

출력

0xe80900
0xe80940
1
1
0
1
0xe80940