12.2 StrBlob类的实现
class StrBlob
{
public:
typedef vector<string>::size_type size_type;
StrBlob():data(make_shared<vector<string>>()){}
StrBlob(initializer_list<string> il) :data(make_shared<vector<string>>(il)) {}
size_type size() const
{
return data->size();
}
bool empty() const
{
return data->empty();
}
void push_back(const string &t)
{
data->push_back(t);
}
void pop_back()
{
check(0, "pop_back on empty StrBlob");
data->pop_back();
}
const string& front()
{
check(0, "front on empty StrBlob");
return data->front();
}
const string& front() const
{
check(0, "front on empty StrBlob");
return data->front();
}
const string& back()
{
check(0, "back on empty StrBlob");
return data->back();
}
const string& back() const
{
check(0, "back on empty StrBlob");
return data->back();
}
private:
shared_ptr<vector<string>> data;
void check(size_type i, const string &msg) const
{
if (i >= data->size())
throw out_of_range(msg);
}
};
12.6&&12.7 编写函数,返回一个动态分配的 int 的vector。将此vector 传递给另一个函数,这个函数读取标准输入,将读入的值保存在 vector 元素中。再将vector传递给另一个函数,打印读入的值。记得在恰当的时刻delete vector。
shared_ptr<vector<string>> alloc_vector()
{
return make_shared<vector<string>>();
}
void assign_vector(shared_ptr<vector<string>> p)
{
string i;
while (cin >> i)
{
p->push_back(i);
}
}
void print_vector(shared_ptr<vector<string>> p)
{
for (auto it : *p)
{
cout << it << " ";
}
cout << endl;
}
int main()
{
auto p = alloc_vector();
assign_vector(p);
print_vector(p);
return 0;
}
12.14 connection函数
struct connection
{
string ip;
int port;
connection(string ip_, int port_) :ip(ip_), port(port_) {}
};
struct destination
{
string ip;
int port;
destination(string ip_, int port_): ip(ip_), port(port_) {}
};
connection connect(destination *pDest)
{
shared_ptr<connection> pConn(new connection(pDest->ip, pDest->port));
cout << "create connection " << pConn.use_count() << endl;
return *pConn;
}
void disconnect(connection pConn)
{
cout << "connection close" << pConn.ip << ": " << pConn.port << endl;
}
void end_connection(connection *pConn)
{
disconnect(*pConn);
}
void f(destination &d)
{
connection conn = connect(&d);
shared_ptr<connection> p(&conn, end_connection);
cout << "connection now " << p.use_count() << endl;
}
int main()
{
destination dest("202.118.176.67", 3316);
f(dest);
system("pause");
return 0;
}
12.16 unique_ptr
int main()
{
unique_ptr<string> p1(new string("str"));
unique<string> p2 = p1; //错误 unique_ptr不能拷贝与赋值 只能够直接初始化
cout << *p1 << endl;
system("pause");
return 0;
}