|
|
@ -1,5 +1,6 @@
|
|
|
|
#include <cassert>
|
|
|
|
#include <cassert>
|
|
|
|
#include <memory>
|
|
|
|
#include <memory>
|
|
|
|
|
|
|
|
#include <vector>
|
|
|
|
|
|
|
|
|
|
|
|
// From Wikipedia.
|
|
|
|
// From Wikipedia.
|
|
|
|
|
|
|
|
|
|
|
@ -21,6 +22,24 @@ void shared_ptr() {
|
|
|
|
assert(p1.use_count() == 0);
|
|
|
|
assert(p1.use_count() == 0);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
void shared_ptr_container() {
|
|
|
|
|
|
|
|
std::shared_ptr<int> p1(new int(5));
|
|
|
|
|
|
|
|
std::shared_ptr<int> p2 = p1; // Both now own the memory.
|
|
|
|
|
|
|
|
assert(p1.use_count() == 2);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
std::vector<std::shared_ptr<int>> v;
|
|
|
|
|
|
|
|
v.push_back(p1);
|
|
|
|
|
|
|
|
v.push_back(p1);
|
|
|
|
|
|
|
|
assert(p1.use_count() == 4);
|
|
|
|
|
|
|
|
p2.reset();
|
|
|
|
|
|
|
|
assert(p1.use_count() == 3);
|
|
|
|
|
|
|
|
assert(p2.use_count() == 0);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
v.pop_back();
|
|
|
|
|
|
|
|
v.pop_back();
|
|
|
|
|
|
|
|
assert(p1.use_count() == 1);
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void weak_ptr() {
|
|
|
|
void weak_ptr() {
|
|
|
|
std::shared_ptr<int> p1(new int(5));
|
|
|
|
std::shared_ptr<int> p1(new int(5));
|
|
|
|
std::weak_ptr<int> wp1 = p1; // p1 owns the memory.
|
|
|
|
std::weak_ptr<int> wp1 = p1; // p1 owns the memory.
|
|
|
@ -50,5 +69,6 @@ void weak_ptr() {
|
|
|
|
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
int main() {
|
|
|
|
shared_ptr();
|
|
|
|
shared_ptr();
|
|
|
|
|
|
|
|
shared_ptr_container();
|
|
|
|
weak_ptr();
|
|
|
|
weak_ptr();
|
|
|
|
}
|
|
|
|
}
|
|
|
|