forked from pezy/CppPrimer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ex12_14.cpp
56 lines (49 loc) · 1.22 KB
/
ex12_14.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
// ex12_14.cpp
// Exercise 12.14
//
// Created by pezy on 12/22/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// Write your own version of a function that uses a shared_ptr to manage a
// connection.
#include <iostream>
#include <string>
#include <memory>
struct connection {
std::string ip;
int port;
connection(std::string ip_, int port_) : ip(ip_), port(port_) {}
};
struct destination {
std::string ip;
int port;
destination(std::string ip_, int port_) : ip(ip_), port(port_) {}
};
connection connect(destination* pDest)
{
std::shared_ptr<connection> pConn(new connection(pDest->ip, pDest->port));
std::cout << "creating connection(" << pConn.use_count() << ")"
<< std::endl;
return *pConn;
}
void disconnect(connection pConn)
{
std::cout << "connection close(" << pConn.ip << ":" << pConn.port << ")"
<< std::endl;
}
void end_connection(connection* pConn)
{
disconnect(*pConn);
}
void f(destination& d)
{
connection conn = connect(&d);
std::shared_ptr<connection> p(&conn, end_connection);
std::cout << "connecting now(" << p.use_count() << ")" << std::endl;
}
int main()
{
destination dest("202.118.176.67", 3316);
f(dest);
}