// 指向一个值为1的int的shared_ptr shared_ptr<int> p3 = make_shared<int>)(1); // 指向一个值为“www”的string的shared_ptr shared_ptr<string> p4 = make_shared<string>(3, "w"); // 指向一个初始化的int,值为0 shared_ptr<int> p5 = make_shared<int>)();
Blob<string> b1;
{ // 新作用域
Blob<string> b2 = { "x", "b", "b" };
b1 = b2;
} // 当离开局部作用域,b2被销毁,然而b2中的元素xbb并不会被销毁
// b1指向最初由b2创建的元素,即“x”, "b", "b",b1依旧可以它们
auto bb = make_shared<string>(2, 'b');
weak_ptr<string> xbb(bb);
if (shared_pr<int> np = xbb.lock()) { // np不为空条件成立
// 在if语句内,np和xbb共享对象
}
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <initializer_list>
using namespace std;
using std::string;
using std::vector;
class StrBlobPtr;
class StrBlob {
public:
friend class StrBlobPtr; // 友元
StrBlobPtr begin(); // 声明StrBlob类中的begin()和end()
StrBlobPtr end(); // 返回一个指向它自身的StrBlobPtr
public:
typedef vector<string>::size_type size_type; // 类型别名,size_type = vector<string>::size_type
StrBlob::StrBlob(initializer_list<string> il) : data(make_shared<vector<string>>(il)) {}; // 接受一个initializer_list参数的构造函数将其参数传 递给对应的vector构造函数,通过拷贝列表
StrBlob::StrBlob() : data(make_shared<vector<string>>()) {}; // 构造函数,初始化data成员,指向动态分配的vector 中的值初始化vector元素
void push_back(const string &t) { data->push_back(t); }
string& StrBlob::front() {
check(0, "front on empty StrBlob");
return data->front();
}
string& StrBlob::back() {
check(0, "back on empty StrBlob");
return data->back();
}
void StrBlob::pop_back() { // 删除尾元素
check(0, "pop_back empty StrBlob");
return data->pop_back();
}
string& front() const { return data->front(); };
string& back() const { return data->back(); };
private:
shared_ptr<vector<string>> data;
void StrBlob::check(size_type i, const string &msg) const { // 检查元素是否存在
if (i >= data->size()) // 若不存在
throw out_of_range(msg); // 抛出异常
}
};
class StrBlobPtr {
public:
StrBlobPtr() : curr(0) {};
StrBlobPtr(StrBlob &a, size_t sz = 0) : wptr(a.data), curr(sz) {};
string & deref() const {
auto p = check(curr, "dereference past end");
return (*p)[curr]; // check成功,返回一个p指针,指向make_shared指向的vector
} // 解引用,make_shared获取vector,用下表运算符返回curr位置上的对象
StrBlobPtr& incr() {
check(curr, "increment past end of StrBlobPtr");
++curr;
return *this;
}
bool operator!=(const StrBlobPtr& p) { return p.curr != curr; }
private:
weak_ptr<vector<string>> wptr;
size_t curr;
shared_ptr<vector<string>> check(size_t i, const string& msg) const
{
auto rent = wptr.lock();
if (!rent)
throw runtime_error("unbound StrBlobPtr");
if (i >= rent->size())
throw out_of_range(msg);
return rent;
}
};
StrBlobPtr StrBlob::begin()
{
return StrBlobPtr(*this);
}
StrBlobPtr StrBlob::end()
{
return StrBlobPtr(*this, data->size());
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有