@@ -8,6 +8,12 @@ Sample use case:
88- how to prevent memory leaks?
99
1010http://en.cppreference.com/w/cpp/memory/unique_ptr
11+
12+ unique_ptr may incur an extra dereferece cost, but it is usually well worth it.
13+
14+ In Java, everything can be though as a smart pointer (shared),
15+ so using this is still more efficient than Java, since C++ can know the exact
16+ lifetime of objects, and release them immediately when they are done.
1117*/
1218
1319#include " common.hpp"
@@ -52,6 +58,12 @@ void manual_ptr_test() {
5258 }
5359}
5460
61+ // Create unique pointer dynamically,
62+ // and transfers ownershipt to caller.
63+ std::unique_ptr<Base> return_unique_ptr () {
64+ return std::unique_ptr<Base>(new Base (1 ));
65+ }
66+
5567int main () {
5668 /* Basic example. */
5769 assert (Base::count == 0 );
@@ -120,13 +132,46 @@ int main() {
120132 /*
121133 # unique_ptr function argments
122134
123- - `std::move` for transfering ownership
135+ - transfering ownership TODO
136+ - use raw pointeres on the interface, and convert it to unique_ptr inside callee
137+ - if you already have an unique_ptr, release() it
138+ - this allows you to not tie down to a specific smart pointer on the function interface
139+ - use unique_ptr on interface and move on caller.
140+ - Advantage: unique_ptr on interface documents ownership transfer,
141+ and prevents callee from passing non new pointer to it by mistake.
124142 - TODO for not transfering ownership:
125- - `const &`
143+ - `const & std::unique_ptr<T> `
126144 - `get()`. Simple and efficient. But how to use it for containers like `vector<std::unique_ptr>`?
145+ - `T&` on function, `*t` on caller. Looks good!
127146
128- http://stackoverflow.com/questions/8114276/how-do-i-pass-a-unique-ptr-argument-to-a-constructor-or-a-functionhttp://stackoverflow.com/questions/8114276/how-do-i-pass-a-unique-ptr-argument-to-a-constructor-or-a-function
147+ - http://stackoverflow.com/questions/8114276/how-do-i-pass-a-unique-ptr-argument-to-a-constructor-or-a-functionhttp://stackoverflow.com/questions/8114276/how-do-i-pass-a-unique-ptr-argument-to-a-constructor-or-a-function
148+ - http://stackoverflow.com/questions/11277249/how-to-pass-stdunique-ptr-around
129149 */
130150 {
131151 }
152+
153+ // Return unique_ptr from function.
154+ {
155+ {
156+ Base::count = 0 ;
157+ auto base = return_unique_ptr ();
158+ assert (Base::count == 1 );
159+ assert (base->i == 1 );
160+ }
161+ assert (Base::count == 0 );
162+ }
163+
164+ #if __cplusplus >= 201402L
165+ // # make_unique
166+ // Does new and puts it inside unique_ptr. Very convenient.
167+ {
168+ {
169+ Base::count = 0 ;
170+ auto base = std::make_unique<Base>(1 );
171+ assert (Base::count == 1 );
172+ assert (base->i == 1 );
173+ }
174+ assert (Base::count == 0 );
175+ }
176+ #endif
132177}
0 commit comments