unique_ptr ownership in C++
One owner at a time: std::unique_ptr deletes what it holds, and only std::move can pass it on.
#include <memory>
#include <string>
#include <utility>
struct Job {
std::string name;
int priority;
};
std::unique_ptr<Job> handoff() {
auto job = std::make_unique<Job>("index", 3);
job->priority = 1;
std::unique_ptr<Job> owner = std::move(job); // job is now null
return owner;
}
How it works
std::make_unique<Job>allocates and constructs in one call; no barenewanywhere.->reaches through the pointer to theJobmembers, same as a raw pointer would.std::movetransfers the allocation toowner, leavingjobnull; returning moves it again, out to the caller.
Keywords and builtins used here
Jobautointreturnstruct
The run, in numbers
- Lines
- 15
- Characters to type
- 283
- Tokens
- 81
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 69 seconds.
Step 3 of 3 in Classes & RAII, step 18 of 27 in Language basics.