12.6
#include<vector>
#include<iostream>
using std::vector;
vector<int> * func() {
auto p = new vector<int>;
return p;
}
vector<int> * func2(vector<int> * p) {
int in;
while (std::cin >> in) {
p->push_back(in);
}
}
void func3(vector<int> * p) {
for (auto a : *p) {
std::cout << a << std::endl;
}
delete p;
}
12.7
#include<vector>
#include<iostream>
#include<memory>
using std::make_shared;
using std::vector;
using spvi = std::shared_ptr<vector<int>>;
auto func4() {
spvi p = make_shared<vector<int>>();
return p;
}
auto func5(spvi p) {
int in;
while (std::cin >> in) {
p->push_back(in);
}
}
void func6(spvi p) {
for (auto a : *p) {
std::cout << a << std::endl;
}
}
12.8
bool b() {
int* p = new int;
// ...
return p;
}
返回的p是一个指针,但是返回类型是bool,会自动转换过去,但是也意味着这段内存将没有机会再被释放掉,会造成内存泄露
12.9
int *q = new int(42), *r = new int(100);
r = q;
auto q2 = make_shared<int>(42), r2 = make_shared<int>(100);
r2 = q2;
r=q会使r和q同时指向 42
而 100 没有被释放也没有机会被释放了,会造成内存泄露
r2=q2,会是 42的计时器加1变成2,而100的计时器减1变为0,系统会释放其内存,没有问题