Manage a resource with unique_ptr
Description: Make a class Resource whose constructor and destructor print a message. Create it with std::make_unique, move it into a function which takes ownership, and see when it is destroyed.
Hint:
- A
unique_ptrcan not be copied, only moved withstd::move.
Solution
#include <iostream>
#include <memory>
struct Resource {
Resource() { std::cout << "created\n"; }
~Resource() { std::cout << "destroyed\n"; }
};
void consume(std::unique_ptr<Resource> r) {
std::cout << "consume has the resource\n";
} // r goes out of scope here: the resource is destroyed
int main() {
auto r = std::make_unique<Resource>();
consume(std::move(r));
std::cout << "after consume, empty: " << (r == nullptr) << '\n';
}
Output
created
consume has the resource
destroyed
after consume, empty: 1
How it works
std::movegives the ownership to the function. After that,rin main is empty.- The destructor ran at the end of
consume, with nodeletein our code.
Read Smart Pointers.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |