-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprotected_destructor.cpp
More file actions
71 lines (59 loc) · 2.39 KB
/
Copy pathprotected_destructor.cpp
File metadata and controls
71 lines (59 loc) · 2.39 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
#include <iostream>
#include <memory>
#include <string>
class IConnection {
public:
virtual void send(const std::string& data) = 0;
virtual bool isConnected() const = 0;
protected:
// non-virtual + protected: client không delete được qua IConnection*
~IConnection() = default;
};
class TcpConnection : public IConnection {
public:
TcpConnection() {
std::cout << "TCP connection created!\n";
}
// public + virtual: xóa qua TcpConnection* (hoặc lớp con của nó) là hợp lệ
~TcpConnection() {
std::cout << "TCP connection destroyed!\n";
}
void send(const std::string& data) override {
std::cout << "Send: " << data << std::endl;
}
bool isConnected() const override {
return true;
}
};
// ---------------------------------------------------------------------
// Factory: trả về ownership rõ ràng bằng smart pointer.
// Không cần friend, không cần hàm destroyConnection() thủ công.
// ---------------------------------------------------------------------
class ConnectionManager {
public:
// Cách 1: trả về kiểu cụ thể -> unique_ptr<TcpConnection> hủy bằng
// destructor public của TcpConnection.
std::unique_ptr<TcpConnection> createTcp() {
return std::make_unique<TcpConnection>();
}
// Cách 2: handle đa hình bằng shared_ptr. Compile được DÙ destructor
// của IConnection là protected, vì shared_ptr "nhớ" deleter gắn với
// kiểu TcpConnection ngay lúc make_shared.
std::shared_ptr<IConnection> openConnection() {
return std::make_shared<TcpConnection>();
}
};
int main() {
ConnectionManager manager;
// --- Dùng qua interface, ownership do smart pointer giữ ---
std::shared_ptr<IConnection> conn = manager.openConnection();
conn->send("Hello");
std::cout << "connected? " << std::boolalpha << conn->isConnected() << '\n';
// Hết scope: shared_ptr gọi ~TcpConnection() (đúng kiểu) -> an toàn.
// IConnection* raw = manager.openConnection().get();
// delete raw; // ❌ ~IConnection() protected
// std::unique_ptr<IConnection> u = // ❌ default_delete cần
// std::make_unique<TcpConnection>(); // gọi ~IConnection()
// IConnection local; // ❌ abstract + dtor protected
return 0;
}