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_ptr can not be copied, only moved with std::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::move gives the ownership to the function. After that, r in main is empty.
  • The destructor ran at the end of consume, with no delete in our code.

Read Smart Pointers.


Learn more about the similar topics:
Tutorials
C++ References and const References
C++ Pointers
C++ Dynamic Memory: new, delete and Smart Pointers
Exercises & Assignments
Swap two numbers using a reference function
Manage a resource with unique_ptr
Interview Questions & Answers
What is the difference between a reference and a pointer in C++?
What is the difference between new and malloc in C++?
What is a memory leak in C++ and how to avoid it?
What is nullptr in C++? What is the difference from NULL?
What is RAII in C++?
What is the difference between unique_ptr, shared_ptr and weak_ptr?
What is const correctness in C++?