12.1.2

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,系统会释放其内存,没有问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值