普通(非模板)类的成员模板

16.21 编写你自己的DebugDelete版本。

#include<iostream>
#include<new>
using namespace std;

class DebugDelete
{
public:
    DebugDelete(ostream &s=cerr):os(s) {}
    template <typename T>
    void operator()(T *p) const
    {
        os<<"deleting unique_ptr "<<endl;
        delete p;
    }
private:
    ostream &os;
};

int main()
{
    double *p=new double;
    DebugDelete d;
    d(p);
    int *ip=new int;
    DebugDelete()(ip);
    return 0;
}

16.22 修改TextQuery程序,令shared_ptr成员使用DebugDelete作为它们的删除器。

TextQuery.h

#ifndef TEXTQUERY_H
#define TEXTQUERY_H
#include<iostream>
#include<string>
#include<fstream>
#include<vector>
#include<memory>
#include<map>
#include<set>
#include<new>
#include"DebugDelete.h"
using namespace std;
class QueryResult;
class TextQuery
{
public:
    using line_no=vector<string>::size_type;
    TextQuery(ifstream&);
    QueryResult query(const string&) const;
    ~TextQuery()
    {
        //DebugDelete()(new vector<string>);
        cout<<"destructing...."<<endl;
    }
private:
    shared_ptr<vector<string>> file;
    map<string,shared_ptr<set<line_no>>> wm;
};
#endif // TEXTQUERY_H

TextQuery.cpp

#include"TextQuery.h"
#include"QueryResult.h"
#include<sstream>
TextQuery::TextQuery(ifstream& is):file(new vector<string>,DebugDelete())
{
    string text;
    while(getline(is,text))
    {
        file->push_back(text);
        int n=file->size()-1;
        string word;
        istringstream line(text);
        while(line>>word)
        {
            auto &lines=wm[word];
            if(!lines)
                lines.reset(new set<line_no>);
            lines->insert(n);
        }
    }
}

QueryResult TextQuery::query(const string& sought) const
{
    static shared_ptr<set<line_no>> nodata(new set<line_no>);
    auto loc=wm.find(sought);
    if(loc!=wm.end())
        return QueryResult(sought,loc->second,file);
    else
        return QueryResult(sought,nodata,file);
}

DebugDelete.h

#include<iostream>
#include<new>
using namespace std;

class DebugDelete
{
public:
    DebugDelete(ostream &s=cerr):os(s) {}
    template <typename T>
    void operator()(T *p) const
    {
        os<<"deleting shared_ptr "<<endl;
        delete p;
    }
private:
    ostream &os;
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值