C++에서 스마트 포인터 사용

Jinku Hu 2023년10월12일
  1. 여러 포인터에 대해std::shared_ptr를 사용하여 C++에서 동일한 객체를 참조합니다
  2. 포인터가 C++에서 주어진 객체를 소유하도록std::unique_ptr를 사용합니다
C++에서 스마트 포인터 사용

이 기사에서는 C++에서 스마트 포인터를 사용하는 방법에 대한 여러 방법을 보여줍니다.

여러 포인터에 대해std::shared_ptr를 사용하여 C++에서 동일한 객체를 참조합니다

동적 메모리의 수동 관리는 실제 프로젝트에서 매우 어렵고 종종 버그의 주요 원인이므로 C++는 스마트 포인터 개념을 별도의 라이브러리로 제공합니다. 스마트 포인터는 일반적으로 일반 포인터 역할을하며 추가 기능을 제공하며, 그중 가장 두드러진 기능은 뾰족한 개체를 자동으로 해제하는 것입니다. 스마트 포인터에는shared_ptrunique_ptr의 두 가지 핵심 유형이 있습니다.

다음 예제 코드는shared_ptr유형의 사용법을 보여줍니다. shared_ptr는 일반적으로 다른 공유 포인터가 가리키는 객체를 참조해야 할 때 사용됩니다. 따라서shared_ptr에는 내부적으로 동일한 개체를 가리키는 포인터 수를 나타내는 관련 카운터가 있습니다. shared_ptr::unique멤버 함수를 사용하여 포인터가 현재 개체를 참조하는 유일한 포인터인지 확인할 수 있습니다. 함수 반환 유형은 부울이고true값은 객체의 독점 소유권을 확인합니다. reset내장 함수는 현재 오브젝트를 첫 번째 매개 변수로 전달 된 오브젝트로 대체합니다. 공유 객체는 객체를 가리키는 마지막shared_ptr가 범위를 벗어나면 삭제됩니다.

#include <iostream>
#include <memory>
#include <vector>

using std::cout;
using std::endl;
using std::string;
using std::vector;

int main() {
  std::shared_ptr<string> p(new string("Arbitrary string"));
  std::shared_ptr<string> p2(p);

  cout << "p : " << p << endl;
  cout << "p2: " << p2 << endl;

  if (!p.unique()) {
    p.reset(new string(*p));
  }
  cout << "p : " << p << endl;

  *p += " modified";
  cout << "*p : " << *p << endl;
  cout << "*p2 : " << *p2 << endl;

  return EXIT_SUCCESS;
}

출력:

p : 0x2272c20
p2: 0x2272c20
p : 0x2273ca0
*p : Arbitrary string modified
*p2 : Arbitrary string

포인터가 C++에서 주어진 객체를 소유하도록std::unique_ptr를 사용합니다

또는 C++는 개체의 유일한 소유자 인unique_ptr유형을 제공합니다. 다른unique_ptr포인터는이를 참조 할 수 없습니다. unique_ptr는 일반 복사 및 할당 작업을 지원하지 않습니다. 여전히 내장 함수 인releasereset을 사용하여 두 개의unique_ptr포인터간에 오브젝트 소유권을 전송할 수 있습니다. release함수 호출은unique_ptr포인터를 널로 만듭니다. unique_ptr이 해제되면reset함수를 호출하여 새 객체 소유권을 할당 할 수 있습니다.

#include <iostream>
#include <memory>
#include <vector>

using std::cout;
using std::endl;
using std::string;
using std::vector;

int main() {
  std::unique_ptr<string> p1(new string("Arbitrary string 2"));

  std::unique_ptr<string> p3(p1.release());

  cout << "*p3 : " << *p3 << endl;
  cout << "p3 : " << p3 << endl;
  cout << "p1 : " << p1 << endl;

  std::unique_ptr<string> p4(new string("Arbitrary string 3"));

  p3.reset(p4.release());
  cout << "*p3 : " << *p3 << endl;
  cout << "p3 : " << p3 << endl;
  cout << "p4 : " << p4 << endl;

  return EXIT_SUCCESS;
}

출력:

*p3 : Arbitrary string 2
p3 : 0x7d4c20
p1 : 0
*p3 : Arbitrary string 3
p3 : 0x7d5c80
p4 : 0
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

관련 문장 - C++ Pointer