C++primer学习:智能指针与动态内存(1)

智能指针是新标准提供的一种管理动态内存的工具,它会自动的释放所管理的内存(如果所有对该对象的引用都不存在了)。定义智能指针的方式有make_shared<T>(args) shared_ptr p(q)

练习:定义一个能够共享对象的类:StrBlob.需要用到智能指针,指向一个动态分配的内存.定义相应的构造函数.用到了initializer_list模板;同时注意重载const版本的front(),back(),否则常量对象不能调用该函数.

#include "iostream"
#include "vector"
#include "memory"
#include "initializer_list"
using namespace std;

class StrBlob
{
public:
    //构造函数
        StrBlob() :data(std::make_shared<vector<string>>()) {};//默认初始化
    StrBlob(initializer_list<string>il) : data(make_shared<vector<string>>(il)){};
    size_t size()const { return data->size(); };
    bool empty() const { return data->empty(); }

    void push_back(const string & s) { data->push_back(s); };


    string & front(){ check(0, "front on empty strblob"); return data->front(); };


    const string & front()const{ "front on empty strblob"; return data->front(); };


private:
    shared_ptr<vector<string>>data;//智能指针
    void check(size_t , const string&)const;
};
void StrBlob:: check(size_t i, const string&msg)const
{
    if (i >= data->size())
        throw out_of_range(msg);
}

int main()
{

    StrBlob test({ "aaa", "bbbb" });
    auto it = test.size();
    auto a = test.front();
    auto b = test.back();
    test.push_back("abcd");
    test.pop_back();
    return 0;
}

==========================================================

new,delete是老式的分配动态内存的办法,但是弊端非常多.下面的函数factory()返回一个动态分配的vector,read读取vector并且从标准输入读取数据存入vector,print()负责输出.

void StrBlob:: check(size_t i, const string&msg)const
{
    if (i >= data->size())
        throw out_of_range(msg);
}
vector<int>* factory()
{
    return  new vector<int>;//很危险

}
void read(istream&is,vector<int>* p)
{
    int i;
    while (is>>i)
        p->push_back(i);
}
void print(vector<int>*p)
{
    for (const auto & it : (*p))
        cout << it << " ";
}
int main()
{
    auto pf = factory();
    read(cin, pf);
    print(pf);
    return 0;
}

用智能指针实现上一题;

Ptvec factory()
{
    return  make_shared<vector<int>>();
}
void read(Ptvec p)
{
    int i;
    while (cin>>i)
        p->push_back(i);
}
void print(Ptvec p)
{
    for (const auto &it : (*p))
        cout << it << " ";
}
int main()
{
    auto pf = factory();
    read(pf);
    print(pf);
    return 0;
}

可以用new创建的指针来对智能指针进行显示的初始化.shared_ptr p(new int(42));不能隐式的初始化.比如shared_ptr<int> p = new int(0);

不要将智能指针与普通指针混用,因为我们不知道什么时候它会释放内存。

智能指针的get函数用来向不能用智能指针的代码传递一个普通指针,但是千万不要用这个普通指针初始化其它智能指针,这会导致两个智能指针相互独立(但是指向同样的内存),有不同的引用计数器.不能实现管理内存.

使用智能指针管理非动态内存:有些类没有定义析构函数很容易忘记显式释放内存.这时候用智能指针可以避免错误.

下面是一个自定义的结构,它没有析构函数,这时候我们用智能指针来管理它:shared_ptr<T>(p,d)d是一个可调用对象,不用让程序员来释放内存.

struct connection
{
    int port;
    int dest;
    int lasting_time;
};
struct destination
{
    int number;
    int cost;
};
connection connect(destination & d)
{
    return(connection{0,d.number, d.cost});
}
void disconnect(connection c)
{
std::cout << "connection close(" <<c.port << ":" <<c.dest << ")"
        << std::endl;
}
void end_connection(connection *p)
{
    disconnect(*p);
}
void f(destination &d)
{
    auto c = connect(d);
    shared_ptr<connection> p(&c, end_connection);
}
int main()
{
    f(destination{ 2, 100 });
    return 0;
}

用lambda表达式代替end_connect函数

这里的参数列表不能省略,

[c](){disconnect(c); }//错误

[c](connection* p){disconnect(c); }//正确,尽管没有用到p.

shared_ptr<connection> p(&c, [](connection* p){disconnect(*p); });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值