- one object == multiple owners
- last referrer destroys the object
- copying allowed
- moving allowed
- can use custom deleter
- can use custom allocator
- Copying and moving is allowed
std::shared_ptr<MyData> source();
void sink(std::shared_ptr<MyData> ptr);
void simpleUsage() {
source();
sink(source());
auto ptr = source();
sink(ptr);
sink(std::move(ptr));
auto p1 = source();
auto p2 = p1;
p2 = std::move(p1);
p1 = p2;
p1 = std::move(p2);
}
std::shared_ptr<MyData> source();
void sink(std::shared_ptr<MyData> ptr);
void collections() {
std::vector<std::shared_ptr<MyData>> v;
v.push_back(source());
auto tmp = source();
v.push_back(tmp);
v.push_back(std::move(tmp));
sink(v[0]);
sink(std::move(v[0]));
}
#include <memory>
#include <map>
#include <string>
class Gadget {};
std::map<std::string, std::shared_ptr<Gadget>> gadgets;
// above wouldn't compile with C++03. Why?
void foo() {
std::shared_ptr<Gadget> p1{new Gadget()}; // reference counter = 1
{
auto p2 = p1; // copy (reference counter == 2)
gadgets.insert(make_pair("mp3", p2)); // copy (reference counter == 3)
p2->use();
} // destruction of p2, reference counter = 2
} // destruction of p1, reference counter = 1
int main() {
foo();
gadgets.clear(); // reference counter = 0 - gadget is removed
}
- What happens here?