回答編集履歴
2
追記
test
CHANGED
@@ -103,3 +103,51 @@
|
|
103
103
|
}
|
104
104
|
|
105
105
|
```
|
106
|
+
|
107
|
+
|
108
|
+
|
109
|
+
vector<int*> を使っても構わんけど、リークの要因になるからオススメしない。
|
110
|
+
|
111
|
+
```C++
|
112
|
+
|
113
|
+
#include<memory>
|
114
|
+
|
115
|
+
#include<vector>
|
116
|
+
|
117
|
+
#include <iostream>
|
118
|
+
|
119
|
+
|
120
|
+
|
121
|
+
int main() {
|
122
|
+
|
123
|
+
std::vector<int*> ints;
|
124
|
+
|
125
|
+
|
126
|
+
|
127
|
+
for ( int i = 0; i < 10; ++i ) {
|
128
|
+
|
129
|
+
ints.push_back(new int(i));
|
130
|
+
|
131
|
+
}
|
132
|
+
|
133
|
+
|
134
|
+
|
135
|
+
// かくにん(と解放)
|
136
|
+
|
137
|
+
for ( int* item : ints ) {
|
138
|
+
|
139
|
+
std::cout << *item << ' ';
|
140
|
+
|
141
|
+
// これ↓を忘れがちだからポインタの集合はお薦めしかねる
|
142
|
+
|
143
|
+
delete item;
|
144
|
+
|
145
|
+
}
|
146
|
+
|
147
|
+
|
148
|
+
|
149
|
+
return 0;
|
150
|
+
|
151
|
+
}
|
152
|
+
|
153
|
+
```
|
1
追記
test
CHANGED
@@ -53,3 +53,53 @@
|
|
53
53
|
}
|
54
54
|
|
55
55
|
```
|
56
|
+
|
57
|
+
|
58
|
+
|
59
|
+
呈示された元コードを活かすなら:
|
60
|
+
|
61
|
+
|
62
|
+
|
63
|
+
```C++
|
64
|
+
|
65
|
+
#include<memory>
|
66
|
+
|
67
|
+
#include<vector>
|
68
|
+
|
69
|
+
#include <iostream>
|
70
|
+
|
71
|
+
|
72
|
+
|
73
|
+
int main() {
|
74
|
+
|
75
|
+
std::vector<std::unique_ptr<int>> ints;
|
76
|
+
|
77
|
+
|
78
|
+
|
79
|
+
for ( int i = 0; i < 10; ++i ) {
|
80
|
+
|
81
|
+
std::unique_ptr<int> up;
|
82
|
+
|
83
|
+
up.reset(new int(i));
|
84
|
+
|
85
|
+
ints.push_back(std::move(up)); // std::moveせよ
|
86
|
+
|
87
|
+
}
|
88
|
+
|
89
|
+
|
90
|
+
|
91
|
+
// かくにん
|
92
|
+
|
93
|
+
for ( auto& item : ints ) {
|
94
|
+
|
95
|
+
std::cout << *item.get() << ' ';
|
96
|
+
|
97
|
+
}
|
98
|
+
|
99
|
+
|
100
|
+
|
101
|
+
return 0;
|
102
|
+
|
103
|
+
}
|
104
|
+
|
105
|
+
```
|