-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmove-semantics.html
More file actions
333 lines (287 loc) · 63.9 KB
/
move-semantics.html
File metadata and controls
333 lines (287 loc) · 63.9 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>C++ | Move Semantics</title>
<meta name="generator" content="VuePress 1.8.2">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="description" content="Using std::move to reduce complexity from O(n²) to O(n), Move semantics, Move constructor, Move assignment, Re-use a moved object, Using move semantics on containers">
<meta property="og:site_name" content="DevTut">
<meta property="og:title" content="C++ | Move Semantics">
<meta property="og:description" content="Using std::move to reduce complexity from O(n²) to O(n), Move semantics, Move constructor, Move assignment, Re-use a moved object, Using move semantics on containers">
<meta property="og:type" content="article">
<meta property="og:url" content="/cpp/move-semantics.html">
<meta property="og:image" content="/logo.png">
<meta name="twitter:title" content="C++ | Move Semantics">
<meta name="twitter:description" content="Using std::move to reduce complexity from O(n²) to O(n), Move semantics, Move constructor, Move assignment, Re-use a moved object, Using move semantics on containers">
<meta name="twitter:url" content="/cpp/move-semantics.html">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="/logo.png">
<meta name="theme-color" content="#ffffff">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="msapplication-TileImage" content="/mstile-150x150.png">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="google-site-verification" content="76_rKXgwMVIjd-axJC_1zPV9OS4mEjvtgjYOWVkAdnQ">
<link rel="preload" href="/assets/css/0.styles.60619e34.css" as="style"><link rel="preload" href="/assets/js/app.1779e102.js" as="script"><link rel="preload" href="/assets/js/3.2cfa8016.js" as="script"><link rel="preload" href="/assets/js/677.0901798b.js" as="script">
<link rel="stylesheet" href="/assets/css/0.styles.60619e34.css">
</head>
<body>
<div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><!----> <span class="site-name">DevTut</span></a> <div class="links"><form id="search-form" role="search" class="algolia-search-wrapper search-box"><input id="algolia-search-input" class="search-query"></form> <nav class="nav-links can-hide"> <a href="https://github.com/devtut/generate" target="_blank" rel="noopener noreferrer" class="repo-link">
GitHub
<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"> <a href="https://github.com/devtut/generate" target="_blank" rel="noopener noreferrer" class="repo-link">
GitHub
<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav> <ul class="sidebar-links"><li><section class="sidebar-group depth-0"><p class="sidebar-heading open"><span>C++</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/cpp/" aria-current="page" class="sidebar-link">Disclaimer</a></li><li><a href="/cpp/getting-started-with-cpp.html" class="sidebar-link">Getting started with C++</a></li><li><a href="/cpp/literals.html" class="sidebar-link">Literals</a></li><li><a href="/cpp/operator-precedence.html" class="sidebar-link">operator precedence</a></li><li><a href="/cpp/floating-point-arithmetic.html" class="sidebar-link">Floating Point Arithmetic</a></li><li><a href="/cpp/bit-operators.html" class="sidebar-link">Bit Operators</a></li><li><a href="/cpp/bit-manipulation.html" class="sidebar-link">Bit Manipulation</a></li><li><a href="/cpp/bit-fields.html" class="sidebar-link">Bit fields</a></li><li><a href="/cpp/arrays.html" class="sidebar-link">Arrays</a></li><li><a href="/cpp/iterators.html" class="sidebar-link">Iterators</a></li><li><a href="/cpp/basic-input-output-in-c.html" class="sidebar-link">Basic input/output in c++</a></li><li><a href="/cpp/loops.html" class="sidebar-link">Loops</a></li><li><a href="/cpp/file-i-o.html" class="sidebar-link">File I/O</a></li><li><a href="/cpp/cpp-streams.html" class="sidebar-link">C++ Streams</a></li><li><a href="/cpp/stream-manipulators.html" class="sidebar-link">Stream manipulators</a></li><li><a href="/cpp/flow-control.html" class="sidebar-link">Flow Control</a></li><li><a href="/cpp/metaprogramming.html" class="sidebar-link">Metaprogramming</a></li><li><a href="/cpp/const-keyword.html" class="sidebar-link">const keyword</a></li><li><a href="/cpp/mutable-keyword.html" class="sidebar-link">mutable keyword</a></li><li><a href="/cpp/friend-keyword.html" class="sidebar-link">Friend keyword</a></li><li><a href="/cpp/type-keywords.html" class="sidebar-link">Type Keywords</a></li><li><a href="/cpp/basic-type-keywords.html" class="sidebar-link">Basic Type Keywords</a></li><li><a href="/cpp/variable-declaration-keywords.html" class="sidebar-link">Variable Declaration Keywords</a></li><li><a href="/cpp/keywords.html" class="sidebar-link">Keywords</a></li><li><a href="/cpp/returning-several-values-from-a-function.html" class="sidebar-link">Returning several values from a function</a></li><li><a href="/cpp/polymorphism.html" class="sidebar-link">Polymorphism</a></li><li><a href="/cpp/references.html" class="sidebar-link">References</a></li><li><a href="/cpp/value-and-reference-semantics.html" class="sidebar-link">Value and Reference Semantics</a></li><li><a href="/cpp/c-function-call-by-value-vs-call-by-reference.html" class="sidebar-link">C++ function "call by value" vs. "call by reference"</a></li><li><a href="/cpp/copying-vs-assignment.html" class="sidebar-link">Copying vs Assignment</a></li><li><a href="/cpp/pointers.html" class="sidebar-link">Pointers</a></li><li><a href="/cpp/pointers-to-members.html" class="sidebar-link">Pointers to members</a></li><li><a href="/cpp/the-this-pointer.html" class="sidebar-link">The This Pointer</a></li><li><a href="/cpp/smart-pointers.html" class="sidebar-link">Smart Pointers</a></li><li><a href="/cpp/classes-structures.html" class="sidebar-link">Classes/Structures</a></li><li><a href="/cpp/function-overloading.html" class="sidebar-link">Function Overloading</a></li><li><a href="/cpp/operator-overloading.html" class="sidebar-link">Operator Overloading</a></li><li><a href="/cpp/function-template-overloading.html" class="sidebar-link">Function Template Overloading</a></li><li><a href="/cpp/virtual-member-functions.html" class="sidebar-link">Virtual Member Functions</a></li><li><a href="/cpp/inline-functions.html" class="sidebar-link">Inline functions</a></li><li><a href="/cpp/special-member-functions.html" class="sidebar-link">Special Member Functions</a></li><li><a href="/cpp/non-static-member-functions.html" class="sidebar-link">Non-Static Member Functions</a></li><li><a href="/cpp/constant-class-member-functions.html" class="sidebar-link">Constant class member functions</a></li><li><a href="/cpp/c-containers.html" class="sidebar-link">C++ Containers</a></li><li><a href="/cpp/namespaces.html" class="sidebar-link">Namespaces</a></li><li><a href="/cpp/header-files.html" class="sidebar-link">Header Files</a></li><li><a href="/cpp/using-declaration.html" class="sidebar-link">Using declaration</a></li><li><a href="/cpp/std-string.html" class="sidebar-link">std::string</a></li><li><a href="/cpp/std-array.html" class="sidebar-link">std::array</a></li><li><a href="/cpp/std-vector.html" class="sidebar-link">std::vector</a></li><li><a href="/cpp/std-map.html" class="sidebar-link">std::map</a></li><li><a href="/cpp/std-optional.html" class="sidebar-link">std::optional</a></li><li><a href="/cpp/std-function-to-wrap-any-element-that-is-callable.html" class="sidebar-link">std::function: To wrap any element that is callable</a></li><li><a href="/cpp/std-forward-list.html" class="sidebar-link">std::forward_list</a></li><li><a href="/cpp/std-pair.html" class="sidebar-link">std::pair</a></li><li><a href="/cpp/std-atomics.html" class="sidebar-link">std::atomics</a></li><li><a href="/cpp/std-variant.html" class="sidebar-link">std::variant</a></li><li><a href="/cpp/std-iomanip.html" class="sidebar-link">std::iomanip</a></li><li><a href="/cpp/std-any.html" class="sidebar-link">std::any</a></li><li><a href="/cpp/std-set-and-std-multiset.html" class="sidebar-link">std::set and std::multiset</a></li><li><a href="/cpp/std-integer-sequence.html" class="sidebar-link">std::integer_sequence</a></li><li><a href="/cpp/using-std-unordered-map.html" class="sidebar-link">Using std::unordered_map</a></li><li><a href="/cpp/standard-library-algorithms.html" class="sidebar-link">Standard Library Algorithms</a></li><li><a href="/cpp/the-iso-c-standard.html" class="sidebar-link">The ISO C++ Standard</a></li><li><a href="/cpp/inline-variables.html" class="sidebar-link">Inline variables</a></li><li><a href="/cpp/random-number-generation.html" class="sidebar-link">Random number generation</a></li><li><a href="/cpp/date-and-time-using-chrono-header.html" class="sidebar-link">Date and time using header</a></li><li><a href="/cpp/sorting.html" class="sidebar-link">Sorting</a></li><li><a href="/cpp/enumeration.html" class="sidebar-link">Enumeration</a></li><li><a href="/cpp/iteration.html" class="sidebar-link">Iteration</a></li><li><a href="/cpp/regular-expressions.html" class="sidebar-link">Regular expressions</a></li><li><a href="/cpp/implementation-defined-behavior.html" class="sidebar-link">Implementation-defined behavior</a></li><li><a href="/cpp/exceptions.html" class="sidebar-link">Exceptions</a></li><li><a href="/cpp/lambdas.html" class="sidebar-link">Lambdas</a></li><li><a href="/cpp/value-categories.html" class="sidebar-link">Value Categories</a></li><li><a href="/cpp/preprocessor.html" class="sidebar-link">Preprocessor</a></li><li><a href="/cpp/data-structures-in-c.html" class="sidebar-link">Data Structures in C++</a></li><li><a href="/cpp/templates.html" class="sidebar-link">Templates</a></li><li><a href="/cpp/expression-templates.html" class="sidebar-link">Expression templates</a></li><li><a href="/cpp/curiously-recurring-template-pattern-crtp.html" class="sidebar-link">Curiously Recurring Template Pattern (CRTP)</a></li><li><a href="/cpp/threading.html" class="sidebar-link">Threading</a></li><li><a href="/cpp/thread-synchronization-structures.html" class="sidebar-link">Thread synchronization structures</a></li><li><a href="/cpp/the-rule-of-three-five-and-zero.html" class="sidebar-link">The Rule of Three, Five, And Zero</a></li><li><a href="/cpp/raii-resource-acquisition-is-initialization.html" class="sidebar-link">RAII: Resource Acquisition Is Initialization</a></li><li><a href="/cpp/rtti-run-time-type-information.html" class="sidebar-link">RTTI: Run-Time Type Information</a></li><li><a href="/cpp/mutexes.html" class="sidebar-link">Mutexes</a></li><li><a href="/cpp/recursive-mutex.html" class="sidebar-link">Recursive Mutex</a></li><li><a href="/cpp/semaphore.html" class="sidebar-link">Semaphore</a></li><li><a href="/cpp/futures-and-promises.html" class="sidebar-link">Futures and Promises</a></li><li><a href="/cpp/atomic-types.html" class="sidebar-link">Atomic Types</a></li><li><a href="/cpp/type-erasure.html" class="sidebar-link">Type Erasure</a></li><li><a href="/cpp/explicit-type-conversions.html" class="sidebar-link">Explicit type conversions</a></li><li><a href="/cpp/unnamed-types.html" class="sidebar-link">Unnamed types</a></li><li><a href="/cpp/type-traits.html" class="sidebar-link">Type Traits</a></li><li><a href="/cpp/return-type-covariance.html" class="sidebar-link">Return Type Covariance</a></li><li><a href="/cpp/layout-of-object-types.html" class="sidebar-link">Layout of object types</a></li><li><a href="/cpp/type-inference.html" class="sidebar-link">Type Inference</a></li><li><a href="/cpp/typedef-and-type-aliases.html" class="sidebar-link">Typedef and type aliases</a></li><li><a href="/cpp/type-deduction.html" class="sidebar-link">type deduction</a></li><li><a href="/cpp/trailing-return-type.html" class="sidebar-link">Trailing return type</a></li><li><a href="/cpp/alignment.html" class="sidebar-link">Alignment</a></li><li><a href="/cpp/perfect-forwarding.html" class="sidebar-link">Perfect Forwarding</a></li><li><a href="/cpp/decltype.html" class="sidebar-link">decltype</a></li><li><a href="/cpp/sfinae-substitution-failure-is-not-an-error.html" class="sidebar-link">SFINAE (Substitution Failure Is Not An Error)</a></li><li><a href="/cpp/undefined-behavior.html" class="sidebar-link">Undefined Behavior</a></li><li><a href="/cpp/overload-resolution.html" class="sidebar-link">Overload resolution</a></li><li><a href="/cpp/move-semantics.html" aria-current="page" class="active sidebar-link">Move Semantics</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/cpp/move-semantics.html#using-std-move-to-reduce-complexity-from-o-n2-to-o-n" class="sidebar-link">Using std::move to reduce complexity from O(n²) to O(n)</a></li><li class="sidebar-sub-header"><a href="/cpp/move-semantics.html#move-semantics-2" class="sidebar-link">Move semantics</a></li><li class="sidebar-sub-header"><a href="/cpp/move-semantics.html#move-constructor" class="sidebar-link">Move constructor</a></li><li class="sidebar-sub-header"><a href="/cpp/move-semantics.html#move-assignment" class="sidebar-link">Move assignment</a></li><li class="sidebar-sub-header"><a href="/cpp/move-semantics.html#re-use-a-moved-object" class="sidebar-link">Re-use a moved object</a></li><li class="sidebar-sub-header"><a href="/cpp/move-semantics.html#using-move-semantics-on-containers" class="sidebar-link">Using move semantics on containers</a></li></ul></li><li><a href="/cpp/pimpl-idiom.html" class="sidebar-link">Pimpl Idiom</a></li><li><a href="/cpp/auto.html" class="sidebar-link">auto</a></li><li><a href="/cpp/copy-elision.html" class="sidebar-link">Copy Elision</a></li><li><a href="/cpp/fold-expressions.html" class="sidebar-link">Fold Expressions</a></li><li><a href="/cpp/unions.html" class="sidebar-link">Unions</a></li><li><a href="/cpp/design-pattern-implementation-in-c.html" class="sidebar-link">Design pattern implementation in C++</a></li><li><a href="/cpp/singleton-design-pattern.html" class="sidebar-link">Singleton Design Pattern</a></li><li><a href="/cpp/user-defined-literals.html" class="sidebar-link">User-Defined Literals</a></li><li><a href="/cpp/memory-management.html" class="sidebar-link">Memory management</a></li><li><a href="/cpp/c-11-memory-model.html" class="sidebar-link">C++11 Memory Model</a></li><li><a href="/cpp/scopes.html" class="sidebar-link">Scopes</a></li><li><a href="/cpp/static-assert.html" class="sidebar-link">static_assert</a></li><li><a href="/cpp/constexpr.html" class="sidebar-link">constexpr</a></li><li><a href="/cpp/one-definition-rule-odr.html" class="sidebar-link">One Definition Rule (ODR)</a></li><li><a href="/cpp/unspecified-behavior.html" class="sidebar-link">Unspecified behavior</a></li><li><a href="/cpp/argument-dependent-name-lookup.html" class="sidebar-link">Argument Dependent Name Lookup</a></li><li><a href="/cpp/attributes.html" class="sidebar-link">Attributes</a></li><li><a href="/cpp/recursion-in-c.html" class="sidebar-link">Recursion in C++</a></li><li><a href="/cpp/arithmitic-metaprogramming.html" class="sidebar-link">Arithmitic Metaprogramming</a></li><li><a href="/cpp/callable-objects.html" class="sidebar-link">Callable Objects</a></li><li><a href="/cpp/client-server-examples.html" class="sidebar-link">Client server examples</a></li><li><a href="/cpp/const-correctness.html" class="sidebar-link">Const Correctness</a></li><li><a href="/cpp/parameter-packs.html" class="sidebar-link">Parameter packs</a></li><li><a href="/cpp/build-systems.html" class="sidebar-link">Build Systems</a></li><li><a href="/cpp/concurrency-with-openmp.html" class="sidebar-link">Concurrency With OpenMP</a></li><li><a href="/cpp/resource-management.html" class="sidebar-link">Resource Management</a></li><li><a href="/cpp/storage-class-specifiers.html" class="sidebar-link">Storage class specifiers</a></li><li><a href="/cpp/linkage-specifications.html" class="sidebar-link">Linkage specifications</a></li><li><a href="/cpp/digit-separators.html" class="sidebar-link">Digit separators</a></li><li><a href="/cpp/c-incompatibilities.html" class="sidebar-link">C incompatibilities</a></li><li><a href="/cpp/side-by-side-comparisons-of-classic-c-examples-solved-via-c-vs-c-11-vs-c-14-vs-c-17.html" class="sidebar-link">Side by Side Comparisons of classic C++ examples solved via C++ vs C++11 vs C++14 vs C++17</a></li><li><a href="/cpp/compiling-and-building.html" class="sidebar-link">Compiling and Building</a></li><li><a href="/cpp/common-compile-linker-errors-gcc.html" class="sidebar-link">Common compile/linker errors (GCC)</a></li><li><a href="/cpp/more-undefined-behaviors-in-c.html" class="sidebar-link">More undefined behaviors in C++</a></li><li><a href="/cpp/unit-testing-in-c.html" class="sidebar-link">Unit Testing in C++</a></li><li><a href="/cpp/c-debugging-and-debug-prevention-tools-techniques.html" class="sidebar-link">C++ Debugging and Debug-prevention Tools & Techniques</a></li><li><a href="/cpp/optimization-in-c.html" class="sidebar-link">Optimization in C++</a></li><li><a href="/cpp/optimization.html" class="sidebar-link">Optimization</a></li><li><a href="/cpp/profiling.html" class="sidebar-link">Profiling</a></li><li><a href="/cpp/refactoring-techniques.html" class="sidebar-link">Refactoring Techniques</a></li><li><a href="/cpp/internationalization-in-c.html" class="sidebar-link">Internationalization in C++</a></li><li><a href="/cpp/contributors.html" class="sidebar-link">The Contributors</a></li></ul></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="move-semantics"><a href="#move-semantics" class="header-anchor">#</a> Move Semantics</h1> <h2 id="using-std-move-to-reduce-complexity-from-o-n2-to-o-n"><a href="#using-std-move-to-reduce-complexity-from-o-n2-to-o-n" class="header-anchor">#</a> Using std::move to reduce complexity from O(n²) to O(n)</h2> <p>C++11 introduced core language and standard library support for <strong>moving</strong> an object. The idea is that when an object <strong>o</strong> is a temporary and one wants a logical copy, then its safe to just pilfer <strong>o</strong>'s resources, such as a dynamically allocated buffer, leaving <strong>o</strong> logically empty but still destructible and copyable.</p> <p>The core language support is mainly</p> <li>
the **rvalue reference** type builder `&&`, e.g., `std::string&&` is an rvalue reference to a `std::string`, indicating that that referred to object is a temporary whose resources can just be pilfered (i.e. moved)
</li> <li>
special support for a **move constructor** `T( T&& )`, which is supposed to efficiently move resources from the specified other object, instead of actually copying those resources, and
</li> <li>
special support for a **move assignment operator** `auto operator=(T&&) -> T&`, which also is supposed to move from the source.
</li> <p>The standard library support is mainly the <code>std::move</code> function template from the <code><utility></code> header. This function produces an rvalue reference to the specified object, indicating that it can be moved from, just as if it were a temporary.</p> <p>For a container actual copying is typically of O(<strong>n</strong>) complexity, where <strong>n</strong> is the number of items in the container, while moving is O(1), constant time. And for an algorithm that logically copies that container <strong>n</strong> times, this can reduce the complexity from the usually impractical O(<strong>n</strong>²) to just linear O(<strong>n</strong>).</p> <p>In his article <a href="http://www.drdobbs.com/cpp/containters-that-never-change/240161543" target="_blank" rel="noopener noreferrer">“Containers That Never Change” in Dr. Dobbs Journal in September 19 2013<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>, Andrew Koenig presented an interesting example of algorithmic inefficiency when using a style of programming where variables are immutable after initialization. With this style loops are generally expressed using recursion. And for some algorithms such as generating a Collatz sequence, the recursion requires logically copying a container:</p> <div class="language-cpp extra-class"><pre class="language-cpp"><code><span class="token comment">// Based on an example by Andrew Koenig in his Dr. Dobbs Journal article</span>
<span class="token comment">// “Containers That Never Change” September 19, 2013, available at</span>
<span class="token comment">// <url: http://www.drdobbs.com/cpp/containters-that-never-change/240161543></span>
<span class="token comment">// Includes here, e.g. <vector></span>
<span class="token keyword">namespace</span> my <span class="token punctuation">{</span>
<span class="token keyword">template</span><span class="token operator"><</span> <span class="token keyword">class</span> <span class="token class-name">Item</span> <span class="token operator">></span>
<span class="token keyword">using</span> Vector_ <span class="token operator">=</span> <span class="token comment">/* E.g. std::vector<Item> */</span><span class="token punctuation">;</span>
<span class="token keyword">auto</span> <span class="token function">concat</span><span class="token punctuation">(</span> Vector_<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span> <span class="token keyword">const</span><span class="token operator">&</span> v<span class="token punctuation">,</span> <span class="token keyword">int</span> <span class="token keyword">const</span> x <span class="token punctuation">)</span>
<span class="token operator">-></span> Vector_<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span>
<span class="token punctuation">{</span>
<span class="token keyword">auto</span> result<span class="token punctuation">{</span> v <span class="token punctuation">}</span><span class="token punctuation">;</span>
result<span class="token punctuation">.</span><span class="token function">push_back</span><span class="token punctuation">(</span> x <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">return</span> result<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">auto</span> <span class="token function">collatz_aux</span><span class="token punctuation">(</span> <span class="token keyword">int</span> <span class="token keyword">const</span> n<span class="token punctuation">,</span> Vector_<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span> <span class="token keyword">const</span><span class="token operator">&</span> result <span class="token punctuation">)</span>
<span class="token operator">-></span> Vector_<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span>
<span class="token punctuation">{</span>
<span class="token keyword">if</span><span class="token punctuation">(</span> n <span class="token operator">==</span> <span class="token number">1</span> <span class="token punctuation">)</span>
<span class="token punctuation">{</span>
<span class="token keyword">return</span> result<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">auto</span> <span class="token keyword">const</span> new_result <span class="token operator">=</span> <span class="token function">concat</span><span class="token punctuation">(</span> result<span class="token punctuation">,</span> n <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">if</span><span class="token punctuation">(</span> n <span class="token operator">%</span> <span class="token number">2</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">)</span>
<span class="token punctuation">{</span>
<span class="token keyword">return</span> <span class="token function">collatz_aux</span><span class="token punctuation">(</span> n<span class="token operator">/</span><span class="token number">2</span><span class="token punctuation">,</span> new_result <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">else</span>
<span class="token punctuation">{</span>
<span class="token keyword">return</span> <span class="token function">collatz_aux</span><span class="token punctuation">(</span> <span class="token number">3</span><span class="token operator">*</span>n <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span> new_result <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">auto</span> <span class="token function">collatz</span><span class="token punctuation">(</span> <span class="token keyword">int</span> <span class="token keyword">const</span> n <span class="token punctuation">)</span>
<span class="token operator">-></span> Vector_<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span>
<span class="token punctuation">{</span>
<span class="token function">assert</span><span class="token punctuation">(</span> n <span class="token operator">!=</span> <span class="token number">0</span> <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">return</span> <span class="token function">collatz_aux</span><span class="token punctuation">(</span> n<span class="token punctuation">,</span> <span class="token generic-function"><span class="token function">Vector_</span><span class="token generic class-name"><span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span> <span class="token comment">// namespace my</span>
<span class="token macro property"><span class="token directive-hash">#</span><span class="token directive keyword">include</span> <span class="token string"><iostream></span></span>
<span class="token keyword">using</span> <span class="token keyword">namespace</span> std<span class="token punctuation">;</span>
<span class="token keyword">auto</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-></span> <span class="token keyword">int</span>
<span class="token punctuation">{</span>
<span class="token keyword">for</span><span class="token punctuation">(</span> <span class="token keyword">int</span> <span class="token keyword">const</span> x <span class="token operator">:</span> my<span class="token double-colon punctuation">::</span><span class="token function">collatz</span><span class="token punctuation">(</span> <span class="token number">42</span> <span class="token punctuation">)</span> <span class="token punctuation">)</span>
<span class="token punctuation">{</span>
cout <span class="token operator"><<</span> x <span class="token operator"><<</span> <span class="token string">' '</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
cout <span class="token operator"><<</span> <span class="token string">'\n'</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><p>Output:</p> <div class="language-cpp extra-class"><pre class="language-cpp"><code><span class="token keyword">using</span> std<span class="token double-colon punctuation">::</span>move<span class="token punctuation">;</span>
<span class="token keyword">auto</span> <span class="token function">concat</span><span class="token punctuation">(</span> Vector_<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span> v<span class="token punctuation">,</span> <span class="token keyword">int</span> <span class="token keyword">const</span> x <span class="token punctuation">)</span>
<span class="token operator">-></span> Vector_<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span>
<span class="token punctuation">{</span>
v<span class="token punctuation">.</span><span class="token function">push_back</span><span class="token punctuation">(</span> x <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// warning: moving a local object in a return statement prevents copy elision [-Wpessimizing-move]</span>
<span class="token comment">// See https://stackoverflow.com/documentation/c%2b%2b/2489/copy-elision</span>
<span class="token comment">// return move( v );</span>
<span class="token keyword">return</span> v<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">auto</span> <span class="token function">collatz_aux</span><span class="token punctuation">(</span> <span class="token keyword">int</span> <span class="token keyword">const</span> n<span class="token punctuation">,</span> Vector_<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span> result <span class="token punctuation">)</span>
<span class="token operator">-></span> Vector_<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span>
<span class="token punctuation">{</span>
<span class="token keyword">if</span><span class="token punctuation">(</span> n <span class="token operator">==</span> <span class="token number">1</span> <span class="token punctuation">)</span>
<span class="token punctuation">{</span>
<span class="token keyword">return</span> result<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">auto</span> new_result <span class="token operator">=</span> <span class="token function">concat</span><span class="token punctuation">(</span> <span class="token function">move</span><span class="token punctuation">(</span> result <span class="token punctuation">)</span><span class="token punctuation">,</span> n <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">struct</span> <span class="token class-name">result</span><span class="token punctuation">;</span> <span class="token comment">// Make absolutely sure no use of `result` after this.</span>
<span class="token keyword">if</span><span class="token punctuation">(</span> n <span class="token operator">%</span> <span class="token number">2</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">)</span>
<span class="token punctuation">{</span>
<span class="token keyword">return</span> <span class="token function">collatz_aux</span><span class="token punctuation">(</span> n<span class="token operator">/</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token function">move</span><span class="token punctuation">(</span> new_result <span class="token punctuation">)</span> <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">else</span>
<span class="token punctuation">{</span>
<span class="token keyword">return</span> <span class="token function">collatz_aux</span><span class="token punctuation">(</span> <span class="token number">3</span><span class="token operator">*</span>n <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token function">move</span><span class="token punctuation">(</span> new_result <span class="token punctuation">)</span> <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">auto</span> <span class="token function">collatz</span><span class="token punctuation">(</span> <span class="token keyword">int</span> <span class="token keyword">const</span> n <span class="token punctuation">)</span>
<span class="token operator">-></span> Vector_<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span>
<span class="token punctuation">{</span>
<span class="token function">assert</span><span class="token punctuation">(</span> n <span class="token operator">!=</span> <span class="token number">0</span> <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">return</span> <span class="token function">collatz_aux</span><span class="token punctuation">(</span> n<span class="token punctuation">,</span> <span class="token generic-function"><span class="token function">Vector_</span><span class="token generic class-name"><span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><p>Here, with g++ and Visual C++ compilers, the number of item copy operations due to vector copy constructor invocations, was exactly 0.</p> <p>The algorithm is necessarily still O(<strong>n</strong>) in the length of the Collatz sequence produced, but this is a quite dramatic improvement: O(<strong>n</strong>²) → O(<strong>n</strong>).</p> <p>With some language support one could perhaps use moving and still express and enforce the immutability of a variable <strong>between its initialization and final move</strong>, after which any use of that variable should be an error. Alas, as of C++14 C++ does not support that. For loop-free code the no use after move can be enforced via a re-declaration of the relevant name as an incomplete <code>struct</code>, as with <code>struct result;</code> above, but this is ugly and not likely to be understood by other programmers; also the diagnostics can be quite misleading.</p> <p>Summing up, the C++ language and library support for moving allows drastic improvements in algorithm complexity, but due the support's incompleteness, at the cost of forsaking the code correctness guarantees and code clarity that <code>const</code> can provide.</p> <div class="language-cpp extra-class"><pre class="language-cpp"><code><span class="token keyword">template</span><span class="token operator"><</span> <span class="token keyword">class</span> <span class="token class-name">Item</span> <span class="token operator">></span>
<span class="token keyword">class</span> <span class="token class-name">Copy_tracking_vector</span>
<span class="token punctuation">{</span>
<span class="token keyword">private</span><span class="token operator">:</span>
<span class="token keyword">static</span> <span class="token keyword">auto</span> <span class="token function">n_copy_ops</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token operator">-></span> <span class="token keyword">int</span><span class="token operator">&</span>
<span class="token punctuation">{</span>
<span class="token keyword">static</span> <span class="token keyword">int</span> value<span class="token punctuation">;</span>
<span class="token keyword">return</span> value<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
vector<span class="token operator"><</span>Item<span class="token operator">></span> items_<span class="token punctuation">;</span>
<span class="token keyword">public</span><span class="token operator">:</span>
<span class="token keyword">static</span> <span class="token keyword">auto</span> <span class="token function">n</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-></span> <span class="token keyword">int</span> <span class="token punctuation">{</span> <span class="token keyword">return</span> <span class="token function">n_copy_ops</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
<span class="token keyword">void</span> <span class="token function">push_back</span><span class="token punctuation">(</span> Item <span class="token keyword">const</span><span class="token operator">&</span> o <span class="token punctuation">)</span> <span class="token punctuation">{</span> items_<span class="token punctuation">.</span><span class="token function">push_back</span><span class="token punctuation">(</span> o <span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
<span class="token keyword">auto</span> <span class="token function">begin</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">const</span> <span class="token punctuation">{</span> <span class="token keyword">return</span> items_<span class="token punctuation">.</span><span class="token function">begin</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
<span class="token keyword">auto</span> <span class="token function">end</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">const</span> <span class="token punctuation">{</span> <span class="token keyword">return</span> items_<span class="token punctuation">.</span><span class="token function">end</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
<span class="token function">Copy_tracking_vector</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token function">Copy_tracking_vector</span><span class="token punctuation">(</span> Copy_tracking_vector <span class="token keyword">const</span><span class="token operator">&</span> other <span class="token punctuation">)</span>
<span class="token operator">:</span> <span class="token function">items_</span><span class="token punctuation">(</span> other<span class="token punctuation">.</span>items_ <span class="token punctuation">)</span>
<span class="token punctuation">{</span> <span class="token function">n_copy_ops</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+=</span> items_<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
<span class="token function">Copy_tracking_vector</span><span class="token punctuation">(</span> Copy_tracking_vector<span class="token operator">&&</span> other <span class="token punctuation">)</span>
<span class="token operator">:</span> <span class="token function">items_</span><span class="token punctuation">(</span> <span class="token function">move</span><span class="token punctuation">(</span> other<span class="token punctuation">.</span>items_ <span class="token punctuation">)</span> <span class="token punctuation">)</span>
<span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre></div><h2 id="move-semantics-2"><a href="#move-semantics-2" class="header-anchor">#</a> Move semantics</h2> <p>Move semantics are a way of moving one object to another in C++. For this, we empty the old object and place everything it had in the new object.</p> <p>For this, we must understand what an rvalue reference is. An rvalue reference (<code>T&&</code> where T is the object type) is not much different than a normal reference (<code>T&</code>, now called lvalue references). But they act as 2 different types, and so, we can make constructors or functions that take one type or the other, which will be necessary when dealing with move semantics.</p> <p>The reason why we need two different types is to specify two different behaviors. Lvalue reference constructors are related to copying, while rvalue reference constructors are related to moving.</p> <p>To move an object, we will use <code>std::move(obj)</code>. This function returns an rvalue reference to the object, so that we can steal the data from that object into a new one. There are several ways of doing this which are discussed below.</p> <p>Important to note is that the use of <code>std::move</code> creates just an rvalue reference.
In other words the statement <code>std::move(obj)</code> does not change the content of obj, while <code>auto obj2 = std::move(obj)</code> (possibly) does.</p> <h2 id="move-constructor"><a href="#move-constructor" class="header-anchor">#</a> Move constructor</h2> <p>Say we have this code snippet.</p> <div class="language-cpp extra-class"><pre class="language-cpp"><code><span class="token keyword">class</span> <span class="token class-name">A</span> <span class="token punctuation">{</span>
<span class="token keyword">public</span><span class="token operator">:</span>
<span class="token keyword">int</span> a<span class="token punctuation">;</span>
<span class="token keyword">int</span> b<span class="token punctuation">;</span>
<span class="token function">A</span><span class="token punctuation">(</span><span class="token keyword">const</span> A <span class="token operator">&</span>other<span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token keyword">this</span><span class="token operator">-></span>a <span class="token operator">=</span> other<span class="token punctuation">.</span>a<span class="token punctuation">;</span>
<span class="token keyword">this</span><span class="token operator">-></span>b <span class="token operator">=</span> other<span class="token punctuation">.</span>b<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre></div><p>To create a copy constructor, that is, to make a function that copies an object and creates a new one, we normally would choose the syntax shown above, we would have a constructor for A that takes an reference to another object of type A, and we would copy the object manually inside the method.</p> <p>Alternatively, we could have written <code>A(const A &) = default;</code> which automatically copies over all members, making use of its copy constructor.</p> <p>To create a move constructor, however, we will be taking an rvalue reference instead of an lvalue reference, like here.</p> <div class="language-cpp extra-class"><pre class="language-cpp"><code><span class="token keyword">class</span> <span class="token class-name">Wallet</span> <span class="token punctuation">{</span>
<span class="token keyword">public</span><span class="token operator">:</span>
<span class="token keyword">int</span> nrOfDollars<span class="token punctuation">;</span>
<span class="token function">Wallet</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token keyword">default</span><span class="token punctuation">;</span> <span class="token comment">//default ctor</span>
<span class="token function">Wallet</span><span class="token punctuation">(</span>Wallet <span class="token operator">&&</span>other<span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token keyword">this</span><span class="token operator">-></span>nrOfDollars <span class="token operator">=</span> other<span class="token punctuation">.</span>nrOfDollars<span class="token punctuation">;</span>
other<span class="token punctuation">.</span>nrOfDollars <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre></div><p>Please notice that we set the old values to <code>zero</code>. The default move constructor (<code>Wallet(Wallet&&) = default;</code>) copies the value of <code>nrOfDollars</code>, as it is a POD.</p> <p>As move semantics are designed to allow 'stealing' state from the original instance, it is important to consider how the original instance should look like after this stealing. In this case, if we would not change the value to zero we would have doubled the amount of dollars into play.</p> <div class="language-cpp extra-class"><pre class="language-cpp"><code>Wallet a<span class="token punctuation">;</span>
a<span class="token punctuation">.</span>nrOfDollars <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
Wallet <span class="token function">b</span> <span class="token punctuation">(</span>std<span class="token double-colon punctuation">::</span><span class="token function">move</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//calling B(B&& other);</span>
std<span class="token double-colon punctuation">::</span>cout <span class="token operator"><<</span> a<span class="token punctuation">.</span>nrOfDollars <span class="token operator"><<</span> std<span class="token double-colon punctuation">::</span>endl<span class="token punctuation">;</span> <span class="token comment">//0</span>
std<span class="token double-colon punctuation">::</span>cout <span class="token operator"><<</span> b<span class="token punctuation">.</span>nrOfDollars <span class="token operator"><<</span> std<span class="token double-colon punctuation">::</span>endl<span class="token punctuation">;</span> <span class="token comment">//1</span>
</code></pre></div><p>Thus we have move constructed an object from an old one.</p> <p>While the above is a simple example, it shows what the move constructor is intended to do. It becomes more useful in more complex cases, such as when resource management is involved.</p> <div class="language- extra-class"><pre class="language-text"><code>
// Manages operations involving a specified type.
// Owns a helper on the heap, and one in its memory (presumably on the stack).
// Both helpers are DefaultConstructible, CopyConstructible, and MoveConstructible.
template<typename T,
template<typename> typename HeapHelper,
template<typename> typename StackHelper>
class OperationsManager {
using MyType = OperationsManager<T, HeapHelper, StackHelper>;
HeapHelper<T>* h_helper;
StackHelper<T> s_helper;
// ...
public:
// Default constructor & Rule of Five.
OperationsManager() : h_helper(new HeapHelper<T>) {}
OperationsManager(const MyType& other)
: h_helper(new HeapHelper<T>(*other.h_helper)), s_helper(other.s_helper) {}
MyType& operator=(MyType copy) {
swap(*this, copy);
return *this;
}
~OperationsManager() {
if (h_helper) { delete h_helper; }
}
// Move constructor (without swap()).
// Takes other's HeapHelper<T>*.
// Takes other's StackHelper<T>, by forcing the use of StackHelper<T>'s move constructor.
// Replaces other's HeapHelper<T>* with nullptr, to keep other from deleting our shiny
// new helper when it's destroyed.
OperationsManager(MyType&& other) noexcept
: h_helper(other.h_helper),
s_helper(std::move(other.s_helper)) {
other.h_helper = nullptr;
}
// Move constructor (with swap()).
// Places our members in the condition we want other's to be in, then switches members
// with other.
// OperationsManager(MyType&& other) noexcept : h_helper(nullptr) {
// swap(*this, other);
// }
// Copy/move helper.
friend void swap(MyType& left, MyType& right) noexcept {
std::swap(left.h_helper, right.h_helper);
std::swap(left.s_helper, right.s_helper);
}
};
</code></pre></div><h2 id="move-assignment"><a href="#move-assignment" class="header-anchor">#</a> Move assignment</h2> <p>Similarly to how we can assign a value to an object with an lvalue reference, copying it, we can also move the values from an object to another without constructing a new one. We call this move assignment. We move the values from one object to another existing object.</p> <p>For this, we will have to overload <code>operator =</code>, not so that it takes an lvalue reference, like in copy assignment, but so that it takes an rvalue reference.</p> <div class="language-cpp extra-class"><pre class="language-cpp"><code><span class="token keyword">class</span> <span class="token class-name">A</span> <span class="token punctuation">{</span>
<span class="token keyword">int</span> a<span class="token punctuation">;</span>
A<span class="token operator">&</span> <span class="token keyword">operator</span><span class="token operator">=</span> <span class="token punctuation">(</span>A<span class="token operator">&&</span> other<span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token keyword">this</span><span class="token operator">-></span>a <span class="token operator">=</span> other<span class="token punctuation">.</span>a<span class="token punctuation">;</span>
other<span class="token punctuation">.</span>a <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">return</span> <span class="token operator">*</span><span class="token keyword">this</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre></div><p>This is the typical syntax to define move assignment. We overload <code>operator =</code> so that we can feed it an rvalue reference and it can assign it to another object.</p> <div class="language-cpp extra-class"><pre class="language-cpp"><code>A a<span class="token punctuation">;</span>
a<span class="token punctuation">.</span>a <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
A b<span class="token punctuation">;</span>
b <span class="token operator">=</span> std<span class="token double-colon punctuation">::</span><span class="token function">move</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//calling A& operator= (A&& other)</span>
std<span class="token double-colon punctuation">::</span>cout <span class="token operator"><<</span> a<span class="token punctuation">.</span>a <span class="token operator"><<</span> std<span class="token double-colon punctuation">::</span>endl<span class="token punctuation">;</span> <span class="token comment">//0</span>
std<span class="token double-colon punctuation">::</span>cout <span class="token operator"><<</span> b<span class="token punctuation">.</span>a <span class="token operator"><<</span> std<span class="token double-colon punctuation">::</span>endl<span class="token punctuation">;</span> <span class="token comment">//1</span>
</code></pre></div><p>Thus, we can move assign an object to another one.</p> <h2 id="re-use-a-moved-object"><a href="#re-use-a-moved-object" class="header-anchor">#</a> Re-use a moved object</h2> <p>You can re-use a moved object:</p> <div class="language-cpp extra-class"><pre class="language-cpp"><code><span class="token keyword">void</span> <span class="token function">consumingFunction</span><span class="token punctuation">(</span>std<span class="token double-colon punctuation">::</span>vector<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span> vec<span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token comment">// Some operations</span>
<span class="token punctuation">}</span>
<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token comment">// initialize vec with 1, 2, 3, 4</span>
std<span class="token double-colon punctuation">::</span>vector<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span> vec<span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token comment">// Send the vector by move</span>
<span class="token function">consumingFunction</span><span class="token punctuation">(</span>std<span class="token double-colon punctuation">::</span><span class="token function">move</span><span class="token punctuation">(</span>vec<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// Here the vec object is in an indeterminate state.</span>
<span class="token comment">// Since the object is not destroyed, we can assign it a new content.</span>
<span class="token comment">// We will, in this case, assign an empty value to the vector,</span>
<span class="token comment">// making it effectively empty</span>
vec <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token comment">// Since the vector as gained a determinate value, we can use it normally.</span>
vec<span class="token punctuation">.</span><span class="token function">push_back</span><span class="token punctuation">(</span><span class="token number">42</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// Send the vector by move again.</span>
<span class="token function">consumingFunction</span><span class="token punctuation">(</span>std<span class="token double-colon punctuation">::</span><span class="token function">move</span><span class="token punctuation">(</span>vec<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><h2 id="using-move-semantics-on-containers"><a href="#using-move-semantics-on-containers" class="header-anchor">#</a> Using move semantics on containers</h2> <p>You can move a container instead of copying it:</p> <div class="language-cpp extra-class"><pre class="language-cpp"><code><span class="token keyword">void</span> <span class="token function">print</span><span class="token punctuation">(</span><span class="token keyword">const</span> std<span class="token double-colon punctuation">::</span>vector<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span><span class="token operator">&</span> vec<span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">auto</span><span class="token operator">&&</span> val <span class="token operator">:</span> vec<span class="token punctuation">)</span> <span class="token punctuation">{</span>
std<span class="token double-colon punctuation">::</span>cout <span class="token operator"><<</span> val <span class="token operator"><<</span> <span class="token string">", "</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
std<span class="token double-colon punctuation">::</span>cout <span class="token operator"><<</span> std<span class="token double-colon punctuation">::</span>endl<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token comment">// initialize vec1 with 1, 2, 3, 4 and vec2 as an empty vector</span>
std<span class="token double-colon punctuation">::</span>vector<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span> vec1<span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
std<span class="token double-colon punctuation">::</span>vector<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span> vec2<span class="token punctuation">;</span>
<span class="token comment">// The following line will print 1, 2, 3, 4</span>
<span class="token function">print</span><span class="token punctuation">(</span>vec1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// The following line will print a new line</span>
<span class="token function">print</span><span class="token punctuation">(</span>vec2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// The vector vec2 is assigned with move assingment.</span>
<span class="token comment">// This will "steal" the value of vec1 without copying it.</span>
vec2 <span class="token operator">=</span> std<span class="token double-colon punctuation">::</span><span class="token function">move</span><span class="token punctuation">(</span>vec1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// Here the vec1 object is in an indeterminate state, but still valid.</span>
<span class="token comment">// The object vec1 is not destroyed,</span>
<span class="token comment">// but there's is no guarantees about what it contains.</span>
<span class="token comment">// The following line will print 1, 2, 3, 4</span>
<span class="token function">print</span><span class="token punctuation">(</span>vec2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div></div> <footer class="page-edit"><div class="edit-link"><a href="https://github.com/devtut/generate/edit/master/docs/cpp/move-semantics.md" target="_blank" rel="noopener noreferrer">Edit this page on GitHub</a> <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></div> <!----></footer> <div class="page-nav"><p class="inner"><span class="prev">
←
<a href="/cpp/overload-resolution.html" class="prev">
Overload resolution
</a></span> <span class="next"><a href="/cpp/pimpl-idiom.html">
Pimpl Idiom
</a>
→
</span></p></div> </main></div><div class="global-ui"><!----></div></div>
<script src="/assets/js/app.1779e102.js" defer></script><script src="/assets/js/3.2cfa8016.js" defer></script><script src="/assets/js/677.0901798b.js" defer></script>
</body>
</html>