-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShared.cpp
More file actions
78 lines (61 loc) · 1.78 KB
/
Shared.cpp
File metadata and controls
78 lines (61 loc) · 1.78 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <memory>
#include <string>
namespace {
// Shared resource rather than copy to optimize memory
struct AppConfig {
std::string server;
int port;
AppConfig(std::string s, int p) : server(std::move(s)), port(p) {
std::cout << "Config loaded\n";
}
void setPort(int p) { port = p; }
~AppConfig() { std::cout << "Config destroyed\n"; }
};
// Module A
class NetworkManager {
public:
explicit NetworkManager(std::shared_ptr<const AppConfig> cfg)
: mConfig(std::move(cfg)) {}
void connect() const {
std::cout << "Connecting to " << mConfig->server << ":" << mConfig->port
<< "\n";
}
private:
// const means we cannot modify config at this point
std::shared_ptr<const AppConfig> mConfig;
};
// Module B
class Logger {
public:
explicit Logger(std::shared_ptr<const AppConfig> cfg)
: mConfig(std::move(cfg)) {}
void log_start() const {
std::cout << "Logging enabled for " << mConfig->server << "\n";
}
private:
std::shared_ptr<const AppConfig> mConfig;
};
void run() {
// auto config = std::make_shared<AppConfig>("api.example.com", 443);
std::shared_ptr<AppConfig> config =
std::make_shared<AppConfig>("test.server.com", 80);
NetworkManager net(config);
Logger logger(config);
net.connect();
logger.log_start();
std::cout << "use_count = " << config.use_count() << "\n";
config->setPort(8080);
net.connect();
logger.log_start();
}
} // namespace
#include "ExampleRegistry.h"
class Shared : public IExample {
public:
std::string group() const override { return "core"; }
std::string name() const override { return "Shared"; }
std::string description() const override { return "Shared Pointer Example"; }
void execute() override { run(); }
};
REGISTER_EXAMPLE(Shared, "core", "Shared");