Зміст курсу
Розумні Вказівники C++
Розумні Вказівники C++
1. Вступ до Розумних Вказівників
Методи Унікального Вказівника
Оскільки std::unique_ptr
є шаблоном класу, він надає різні методи для безпечного управління собою.
main
#include <iostream> #include <memory> struct Sample { Sample(int v) : value(v) {} int value; void GetValue() { std::cout << "Value: " << value << std::endl; } }; int main() { // Creating a `unique_ptr` std::unique_ptr<Sample> p_first = std::make_unique<Sample>(10); // Using `get()` to retrieve the raw pointer Sample* p_raw = p_first.get(); std::cout << "Raw pointer value: " << p_raw->value << std::endl; // Using `release()` to transfer ownership Sample* p_released = p_first.release(); if (!p_first) std::cout << "p_first is now empty after release.\n"; // Manually delete the released pointer to avoid memory leak delete p_released; // Resetting the `unique_ptr` p_first.reset(new Sample(20)); p_first->GetValue(); // Using `swap()` with another `unique_ptr` std::unique_ptr<Sample> p_second = std::make_unique<Sample>(30); p_first.swap(p_second); p_first->GetValue(); // Now `p_first` owns `p_second` object // Dereferencing the pointer std::cout << "Dereferencing p_first: " << (*p_first).value << std::endl; // Accessing members using `->` operator p_first->GetValue(); }
Все було зрозуміло?
Дякуємо за ваш відгук!
Секція 2. Розділ 5