回答編集履歴
1
修正
test
CHANGED
@@ -5,6 +5,8 @@
|
|
5
5
|
#include <iostream>
|
6
6
|
|
7
7
|
#include <vector>
|
8
|
+
|
9
|
+
#include <memory>
|
8
10
|
|
9
11
|
|
10
12
|
|
@@ -34,27 +36,25 @@
|
|
34
36
|
|
35
37
|
int main() {
|
36
38
|
|
37
|
-
std::vector<Base
|
39
|
+
std::vector<std::unique_ptr<Base>> vec;
|
38
40
|
|
39
|
-
vec.push_back(ne
|
41
|
+
vec.push_back(std::make_unique<Base>());
|
40
42
|
|
41
|
-
vec.push_back(ne
|
43
|
+
vec.push_back(std::make_unique<Derived>());
|
42
44
|
|
43
|
-
vec.push_back(ne
|
45
|
+
vec.push_back(std::make_unique<Base>());
|
44
46
|
|
45
|
-
vec.push_back(ne
|
47
|
+
vec.push_back(std::make_unique<Derived>());
|
46
48
|
|
47
49
|
|
48
50
|
|
49
|
-
for (
|
51
|
+
for ( auto& item : vec ) {
|
50
52
|
|
51
|
-
Derived* der = dynamic_cast<Derived*>(item);
|
53
|
+
Derived* der = dynamic_cast<Derived*>(item.get());
|
52
54
|
|
53
55
|
if ( der ) { der->derived_fn(); }
|
54
56
|
|
55
57
|
else { item->base_fn(); }
|
56
|
-
|
57
|
-
delete item;
|
58
58
|
|
59
59
|
}
|
60
60
|
|