Ownership
Unique Ptr
std::unique_ptr gives one owner responsibility for an object.
Unique Ptr
unique_ptr.cpp
#include <iostream>
#include <memory>
#include <string>
class Note {
private:
std::string text;
public:
Note(std::string value) {
text = value;
}
std::string read() {
return text;
}
};
int main() {
std::string text = ;
std::unique_ptr<Note> note = std::make_unique<Note>(text);
std::cout << "note=" << note->read() << std::endl;
std::cout << "owned=" << (note != nullptr) << std::endl;
return 0;
}
#include <iostream>
#include <memory>
#include <string>
class Note {
private:
std::string text;
public:
Note(std::string value) {
text = value;
}
std::string read() {
return text;
}
};
int main() {
std::string text = ;
std::unique_ptr<Note> note = std::make_unique<Note>(text);
std::cout << "note=" << note->read() << std::endl;
std::cout << "owned=" << (note != nullptr) << std::endl;
return 0;
}
#include <iostream>
#include <memory>
#include <string>
class Note {
private:
std::string text;
public:
Note(std::string value) {
text = value;
}
std::string read() {
return text;
}
};
int main() {
std::string text = ;
std::unique_ptr<Note> note = std::make_unique<Note>(text);
std::cout << "note=" << note->read() << std::endl;
std::cout << "owned=" << (note != nullptr) << std::endl;
return 0;
}
unique ownership
A `std::unique_ptr` deletes its object automatically when the owner goes out of scope.