string vacation("I wandered lonely as a cloud.");
shared_ptr<string> pvac(&vacation); // No
#include<iostream>
#include<memory>
void foo(std::shared_ptr<int> i) {
(*i)++;
}
int main() {
// auto pointer = new int(10); // illegal, no direct assignment
// Constructed a std::shared_ptr
auto pointer = std::make_shared<int>(10);
foo(pointer);
std::cout << *pointer << std::endl; // 11
// The shared_ptr will be destructed before leaving the scope
return 0;
}
struct A;
struct B;
struct A {
std::shared_ptr<B> pointer;
~A() {
std::cout << "A 被销毁" << std::endl;
}
};
struct B {
std::shared_ptr<A> pointer;
~B() {
std::cout << "B 被销毁" << std::endl;
}
};
int main() {
auto a = std::make_shared<A>();
auto b = std::make_shared<B>();
a->pointer = b;
b->pointer = a;
}
unique_ptr<int> make_int(int n) {
return unique_ptr<int>(new int(n));
}
void show(unique_ptr<int> &p1) {
cout << *a << ' ';
}
int main() {
...
vector<unique_ptr<int> > vp(size);
for(int i = 0; i < vp.size(); i++) {
vp[i] = make_int(rand() % 1000); // copy temporary unique_ptr
}
vp.push_back(make_int(rand() % 1000)); // ok because arg is temporary
for_each(vp.begin(), vp.end(), show); // use for_each()
...
}
unique_ptr<int> pup(make_int(rand() % 1000)); // ok
shared_ptr<int> spp(pup); // not allowed, pup as lvalue
shared_ptr<int> spr(make_int(rand() % 1000)); // ok