Smart pointers: unique_ptr and shared_ptr
In week 5 you saw RAII with a class that reserved memory in the constructor and released it in the destructor. Smart pointers are exactly that, already written and tested by the standard library: objects that behave like pointers but automatically release what they point to. With them you almost never need to write new or delete, and you eliminate two whole classes of errors: memory leaks (forgetting to release) and double frees (releasing twice). They are included with the <memory> header and are the modern way to manage dynamic objects, especially in polymorphic hierarchies like those of week 6.
unique_ptr: a single owner
std::unique_ptr<T> represents exclusive ownership: only one pointer owns the object, and when that pointer is destroyed, the object is released. It is created with std::make_unique<T>(arguments), which is safer and shorter than using new. It cannot be copied (two owners would break the rule), but it can be moved with std::move: ownership passes to another and the original is left empty (nullptr). It is used like a normal pointer: -> accesses members, * the object, get() returns the raw pointer without giving up ownership, and reset() releases early. It is your default choice: it costs the same as a raw pointer.
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
};
class Square : public Shape {
public:
explicit Square(double side) : side_{side} {}
double area() const override { return side_ * side_; }
private:
double side_;
};
class Rect : public Shape {
public:
Rect(double w, double h) : w_{w}, h_{h} {}
double area() const override { return w_ * h_; }
private:
double w_;
double h_;
};
int main() {
std::unique_ptr<Shape> a = std::make_unique<Square>(3.0);
std::cout << a->area() << '\n'; // 9
// std::unique_ptr<Shape> b = a; // error: cannot copy
std::unique_ptr<Shape> b = std::move(a); // ownership moves to b
std::cout << (a == nullptr) << '\n'; // 1 (a is empty now)
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Square>(2.0));
shapes.push_back(std::make_unique<Rect>(2.0, 5.0));
shapes.push_back(std::move(b));
double total{0.0};
for (const auto& s : shapes) {
total += s->area();
}
std::cout << "total = " << total << '\n'; // total = 23
return 0; // every Shape is released automatically
}shared_ptr and weak_ptr
Sometimes several objects need to share another and none knows who will finish last. For that there is std::shared_ptr<T>, which keeps a reference count: each copy increments it, each destruction decrements it, and the object is released when it reaches zero. It is created with std::make_shared<T>(...) and use_count() shows how many owners there are. It has a somewhat higher cost, so do not use it out of habit: choose unique_ptr and move to shared_ptr only when sharing ownership is real. Its big danger is cycles: if A has a shared_ptr to B and B one to A, the count never reaches zero and there is a leak. It is broken with std::weak_ptr, an observer that does not count as an owner.
#include <iostream>
#include <memory>
#include <string>
#include <utility>
struct Config {
std::string name;
explicit Config(std::string n) : name{std::move(n)} {
std::cout << "config " << name << " created\n";
}
~Config() { std::cout << "config " << name << " destroyed\n"; }
};
int main() {
std::shared_ptr<Config> first = std::make_shared<Config>("main");
std::cout << "owners: " << first.use_count() << '\n'; // owners: 1
{
std::shared_ptr<Config> second = first; // copy shares ownership
std::cout << "owners: " << first.use_count() << '\n'; // owners: 2
} // second goes away, the object stays alive
std::cout << "owners: " << first.use_count() << '\n'; // owners: 1
std::weak_ptr<Config> observer = first; // does not own
if (auto locked = observer.lock()) { // temporary owner
std::cout << "still alive: " << locked->name << '\n';
}
first.reset(); // last owner released
std::cout << "expired: " << observer.expired() << '\n'; // expired: 1
return 0;
}
// output order: config main created, owners 1, 2, 1, still alive: main,
// config main destroyed, expired: 1Common mistakes: creating two unique_ptr from the same raw pointer (both will try to release it), calling delete on what get() returns, and using a unique_ptr after moving it (it is empty and dereferencing it is undefined behavior). The fix for all three is the same: always create with make_unique or make_shared, do not mix raw pointers with owners and treat a moved-from object as empty.
✎ मेरे नोट्स
केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर