SlideShare a Scribd company logo
1 of 13
Arindam Mukherjee 
Pune C++ and Boost Meetup 
C++11 MOVE SEMANTICS
Copying objects is bad 
 Extra memory, extra CPU cycles to copy. 
 May allocate heap memory, file descriptors, 
etc. 
 May fail.
Temporaries 
 Objects not bound to a variable name 
 Lifetime limited to the statement that 
creates them 
 Examples: 
std::string s1, s2, s3; 
std::string getName(); // prototype 
std::string s4 = s1 + s2 + s3; // may copy 
std::string s5 = getName(); // may copy
Return Value Optimization 
 Copy elision: optimize copies, even when 
they have side effects 
 RVO: Elide copying of a returned temporary. 
std::string getName() { return "foo"; } 
std::string name = getName(); 
 Named RVO: Elide copying of a named 
variable when returned from a function. 
std::string getName() { 
std::string s = "foo"; 
return s; }
RVO: no guarantees 
 May not take effect in: 
- Debug builds. 
- Many but the most simple cases: 
- Returning different named objects from 
different return statements disables NRVO. 
- NRVO does not mix with RVO.
Move, not copy 
 Do a shallow copy to the destination 
 Reset the source and stop using it 
 Useful when: 
- You anyway can’t use the source later: 
std::string s = s1 + s2; 
// s1 + s2 is a temporary 
- You know you won’t use the source later. 
- Copying is expensive and can fail.
l-value, r-value 
 l-values: expressions with durable address. 
May not be ok to move from. 
int x = 5;foo(x); 
char arr[16];arr[5] = 20; 
 r-values: expressions without a durable 
address – temporaries – always ok to move 
from. 
const string& s = string("Foo"), s2, s3; 
setName(getName()); 
s3 = s + s2;
Overload on l- && r-values 
 foo(string& s); // foo(s); 
foo(const string& s); // foo(s1 + s2); 
 Does not work because to move from, we 
need a mutable reference. 
 New class of mutable references – r-value 
references: 
foo(string& s); // foo(s); 
foo(string&& s); // foo(s1 + 2); 
// foo(getName())
Move: Overloading copy 
 Copy suite: 
string(const string& that); 
string& operator=(const string& rhs); 
 Move suite: 
string(string&& that) noexcept; 
string& operator=(string&& rhs) noexcept;
Implementing move 
 X&& var only says it is ok to move from var. 
 foo(X&& var) says foo may move from var. 
 Implementer of foo still has to code the 
actual move. 
 Define a nothrow swap function that 
exchanges pointers and primitive types or 
delegates to other swaps. Swap source with 
target. 
 Make sure source is destructible after swap.
Return by value 
 Return by value prefers move over copy. 
std::string getName() { 
std::string s1; 
if (s1.size() > 0) {return s1;} //move 
else {return string("default");} // rvo 
} 
std::string s1 = getName(); // rvo or move
Moving l-values 
 You know you won’t use the source object 
after this, but compiler doesn’t – so tell it. 
foo(string& s); // 1 
foo(string&& s); // 2 
std::string s("Hello"); 
foo(s); // calls 1 
foo(std::move(s)); // calls 2 
 std::move casts the l-value expression to an r-value 
expression.
Thank you! 
 Q & A 
 Thomas Becker’s C++ Rvalue references 
explained: http://bit.ly/1ACRnAe

More Related Content

What's hot

What's hot (20)

Variadic functions
Variadic functionsVariadic functions
Variadic functions
 
R/C++ talk at earl 2014
R/C++ talk at earl 2014R/C++ talk at earl 2014
R/C++ talk at earl 2014
 
C++11
C++11C++11
C++11
 
Rcpp11 useR2014
Rcpp11 useR2014Rcpp11 useR2014
Rcpp11 useR2014
 
Reconstruction
ReconstructionReconstruction
Reconstruction
 
A698111855 22750 26_2018_finite
A698111855 22750 26_2018_finiteA698111855 22750 26_2018_finite
A698111855 22750 26_2018_finite
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
20190221 fourier series
20190221 fourier series20190221 fourier series
20190221 fourier series
 
Dependent voltage source (vsource)
Dependent voltage source (vsource)Dependent voltage source (vsource)
Dependent voltage source (vsource)
 
Hot С++: Universal References And Perfect Forwarding
Hot С++: Universal References And Perfect ForwardingHot С++: Universal References And Perfect Forwarding
Hot С++: Universal References And Perfect Forwarding
 
Promise of an API
Promise of an APIPromise of an API
Promise of an API
 
[C++ Korea] Effective Modern C++ Study item 34 36
[C++ Korea] Effective Modern C++ Study item 34 36[C++ Korea] Effective Modern C++ Study item 34 36
[C++ Korea] Effective Modern C++ Study item 34 36
 
When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)
 
Rcpp11 genentech
Rcpp11 genentechRcpp11 genentech
Rcpp11 genentech
 
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
BeepBeep 3: A declarative event stream query engine (EDOC 2015)BeepBeep 3: A declarative event stream query engine (EDOC 2015)
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
 
Activity Recognition Through Complex Event Processing: First Findings
Activity Recognition Through Complex Event Processing: First Findings Activity Recognition Through Complex Event Processing: First Findings
Activity Recognition Through Complex Event Processing: First Findings
 
Loops (1)
Loops (1)Loops (1)
Loops (1)
 
The Little Register Allocator
The Little Register AllocatorThe Little Register Allocator
The Little Register Allocator
 
scala-gopher: async implementation of CSP for scala
scala-gopher:  async implementation of CSP  for  scalascala-gopher:  async implementation of CSP  for  scala
scala-gopher: async implementation of CSP for scala
 
Semaphore
SemaphoreSemaphore
Semaphore
 

Similar to C++11 move semantics

Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
SyedHaroonShah4
 
The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019
The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019
The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019
corehard_by
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
Eelco Visser
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
Thomas Johnston
 

Similar to C++11 move semantics (20)

The_Borrow_Checker.pdf
The_Borrow_Checker.pdfThe_Borrow_Checker.pdf
The_Borrow_Checker.pdf
 
C++ Strings.ppt
C++ Strings.pptC++ Strings.ppt
C++ Strings.ppt
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect Forwarding
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019
The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019
The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsHot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move Semantics
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
 
Hot C++: New Style of Arguments Passing
Hot C++: New Style of Arguments PassingHot C++: New Style of Arguments Passing
Hot C++: New Style of Arguments Passing
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
 
Rustlabs Quick Start
Rustlabs Quick StartRustlabs Quick Start
Rustlabs Quick Start
 

Recently uploaded

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 

C++11 move semantics

  • 1. Arindam Mukherjee Pune C++ and Boost Meetup C++11 MOVE SEMANTICS
  • 2. Copying objects is bad  Extra memory, extra CPU cycles to copy.  May allocate heap memory, file descriptors, etc.  May fail.
  • 3. Temporaries  Objects not bound to a variable name  Lifetime limited to the statement that creates them  Examples: std::string s1, s2, s3; std::string getName(); // prototype std::string s4 = s1 + s2 + s3; // may copy std::string s5 = getName(); // may copy
  • 4. Return Value Optimization  Copy elision: optimize copies, even when they have side effects  RVO: Elide copying of a returned temporary. std::string getName() { return "foo"; } std::string name = getName();  Named RVO: Elide copying of a named variable when returned from a function. std::string getName() { std::string s = "foo"; return s; }
  • 5. RVO: no guarantees  May not take effect in: - Debug builds. - Many but the most simple cases: - Returning different named objects from different return statements disables NRVO. - NRVO does not mix with RVO.
  • 6. Move, not copy  Do a shallow copy to the destination  Reset the source and stop using it  Useful when: - You anyway can’t use the source later: std::string s = s1 + s2; // s1 + s2 is a temporary - You know you won’t use the source later. - Copying is expensive and can fail.
  • 7. l-value, r-value  l-values: expressions with durable address. May not be ok to move from. int x = 5;foo(x); char arr[16];arr[5] = 20;  r-values: expressions without a durable address – temporaries – always ok to move from. const string& s = string("Foo"), s2, s3; setName(getName()); s3 = s + s2;
  • 8. Overload on l- && r-values  foo(string& s); // foo(s); foo(const string& s); // foo(s1 + s2);  Does not work because to move from, we need a mutable reference.  New class of mutable references – r-value references: foo(string& s); // foo(s); foo(string&& s); // foo(s1 + 2); // foo(getName())
  • 9. Move: Overloading copy  Copy suite: string(const string& that); string& operator=(const string& rhs);  Move suite: string(string&& that) noexcept; string& operator=(string&& rhs) noexcept;
  • 10. Implementing move  X&& var only says it is ok to move from var.  foo(X&& var) says foo may move from var.  Implementer of foo still has to code the actual move.  Define a nothrow swap function that exchanges pointers and primitive types or delegates to other swaps. Swap source with target.  Make sure source is destructible after swap.
  • 11. Return by value  Return by value prefers move over copy. std::string getName() { std::string s1; if (s1.size() > 0) {return s1;} //move else {return string("default");} // rvo } std::string s1 = getName(); // rvo or move
  • 12. Moving l-values  You know you won’t use the source object after this, but compiler doesn’t – so tell it. foo(string& s); // 1 foo(string&& s); // 2 std::string s("Hello"); foo(s); // calls 1 foo(std::move(s)); // calls 2  std::move casts the l-value expression to an r-value expression.
  • 13. Thank you!  Q & A  Thomas Becker’s C++ Rvalue references explained: http://bit.ly/1ACRnAe